#!/bin/bash

set -euo pipefail

sed -ri 's/^.*FORCE.*$/export FORCE=yes/' /ngcp-fallback/etc/ngcp-installer/config_deploy.inc
sed -ri "s|^.*SIPWISE_URL.*$|export SIPWISE_URL=${REPOS_BASE_URL}|" /ngcp-fallback/etc/ngcp-installer/config_deploy.inc

ppa_num=$(ngcpcfg get bootenv.ppa.size 2>/dev/null || ngcpcfg values bootenv.ppa.size 2>/dev/null)
declare -a PPA
if [[ "${ppa_num}" -ne 0 ]]; then
  ppa_num=$((ppa_num - 1))
  count=0
  while [[ "${count}" -le "${ppa_num}" ]]; do
    PPA+=("$(ngcpcfg get bootenv.ppa.${count}.name 2>/dev/null || ngcpcfg values bootenv.ppa.${count}.name 2>/dev/null)")
    count=$(( count + 1 ))
  done
fi

sed -ri "s/^.*NGCP_PPA=.*$/export NGCP_PPA='${PPA[*]}'/" /ngcp-fallback/etc/ngcp-installer/config_deploy.inc

echo "Running 'eatmydata ngcp-installer' inside /ngcp-fallback chroot"

export UPGRADE_MODE=true
chroot /ngcp-fallback eatmydata ngcp-installer

if dpkg-query -s ngcp-support-noaccess &>/dev/null; then
  echo "The package ngcp-support-noaccess is installed on FROM system so install it to NEW system"
  # shellcheck disable=SC2086
  chroot /ngcp-fallback ${APT_CMD} ${APT_OPTS} install ngcp-support-noaccess
fi

echo "Sync-ing to avoid effects of 'eatmydata' in case of crash..."
sync
echo "... sync-ing done"

# Files to remove
FILES=(/ngcp-fallback/etc/mysql/my.cnf.migrated /ngcp-fallback/etc/mysql/my.cnf.fallback /ngcp-fallback/etc/mysql/my.cnf.dpkg-dist)
for file in "${FILES[@]}"; do
  if [[ -f "${file}" ]]; then
    echo "Removing unnecessary '${file}'"
    rm "${file}"
  else
    echo "File '${file}' is missing, OK here"
  fi
done
