#!/bin/bash

set -e

export DIST="trixie"
export BACKUP="${BACKUP:-/ngcp-data/backup/ngcp-upgrade/ngcp-${UPGRADE_VERSION}/}"
export NGCP_NODENAME="/etc/ngcp_nodename"
export DB_CFG_FILE="/etc/ngcp-config/cfg_schema.db"
export DO_DB_BACKUP="${DO_DB_BACKUP:-yes}"
export CONFIRM_STEP_BY_STEP="${CONFIRM_STEP_BY_STEP:-no}"

export LC_ALL=C
export LANG=C

# be as non-interactive as possible
export APT_LISTCHANGES_FRONTEND=none
export APT_LISTBUGS_FRONTEND=none
export DEBIAN_PRIORITY=critical
export DEBIAN_FRONTEND=noninteractive

export APT_CMD="apt-get"
export APT_OPTS="-y -o DPkg::Options::=--force-confnew"

export CONFIG_YML="/etc/ngcp-config/config.yml"
export CONSTANTS_YML="/etc/ngcp-config/constants.yml"
export NETWORK_YML="/etc/ngcp-config/network.yml"

export APPROX_RW_PORT="9999"
export APPROX_RO_PORT="9998"

CE_EDITION=false
PRO_EDITION=false
CARRIER_EDITION=false

if ! [[ -f /etc/default/ngcp-roles ]]; then
  echo "Missing file /etc/default/ngcp-roles, cannot continue!" >&2
  exit 1
fi

# shellcheck disable=SC1091
. /etc/default/ngcp-roles

case "${NGCP_TYPE}" in
  carrier)
    echo "Sipwise C5 CARRIER detected..."
    CARRIER_EDITION=true
    ;;
  sppro)
    echo "Sipwise C5 PRO detected..."
    PRO_EDITION=true
    ;;
  spce)
    echo "Sipwise C5 CE detected..."
    CE_EDITION=true
    ;;
esac

export CE_EDITION
export PRO_EDITION
export CARRIER_EDITION

if "${CE_EDITION}"; then
  REPOS_BASE_URL="https://deb.sipwise.com"
else
  ngcp_mgmt_node="/etc/ngcp_mgmt_node"
  if [[ ! -f "${ngcp_mgmt_node}" ]]; then
    echo "Missing file ${ngcp_mgmt_node}, cannot continue!" >&2
    exit 1
  fi

  mgmt_node="$(cat ${ngcp_mgmt_node})"
  if [[ -z "${mgmt_node}" ]]; then
    echo "Missing management node name! Check content of file ${ngcp_mgmt_node}, cannot continue!" >&2
    exit 1
  fi

  REPOS_BASE_URL="http://${mgmt_node}:${APPROX_RO_PORT}"
fi

if "${CE_EDITION}"; then
  APPROX_IP_URL="${REPOS_BASE_URL}"
  DEBIAN_REPO_URL="https://debian.sipwise.com"
elif "${PRO_EDITION}"; then
  APPROX_PORT=$(ngcpcfg get bootenv.ro_port 2>/dev/null || ngcpcfg values bootenv.ro_port 2>/dev/null)
  APPROX_IP_URL=$(getent hosts sp | awk '{print $1}')
  APPROX_IP_URL="http://${APPROX_IP_URL}:${APPROX_PORT}"
  DEBIAN_REPO_URL="${APPROX_IP_URL}"
elif "${CARRIER_EDITION}"; then
  APPROX_PORT=$(ngcpcfg get bootenv.ro_port 2>/dev/null || ngcpcfg values bootenv.ro_port 2>/dev/null)
  APPROX_IP_URL=$(getent hosts web01 | awk '{print $1}')
  APPROX_IP_URL="http://${APPROX_IP_URL}:${APPROX_PORT}"
  DEBIAN_REPO_URL="${APPROX_IP_URL}"
fi

export REPOS_BASE_URL
export APPROX_IP_URL
export DEBIAN_REPO_URL

CURRENT_PARTITION="$(findmnt --target / --output SOURCE --noheadings)"
TO_PARTITION=''
if [[ "${CURRENT_PARTITION}" =~ ngcp-root ]]; then
  TO_PARTITION='/dev/mapper/ngcp-fallback'
else
  TO_PARTITION='/dev/mapper/ngcp-root'
fi

export TO_PARTITION
export CURRENT_PARTITION
