#!/bin/bash
# mr7.4: Perform check about PPAs (TT#44268).

set -e
set -E

die() {
  local message="$*"

  echo "ERROR: ${message}" >&2
  exit 1
}

request_confirmation() {
  if [[ "${FORCE_UPGRADE}" = "true" ]]; then
    echo "Forcing as requested via environment variable FORCE_UPGRADE."
    return
  fi

  while true; do
    echo -n "Should we perform the operation? (yes/no): "
    read -r answer
    case "${answer,,}" in
      yes)
        echo "Performing as requested."
        return 0
        ;;
      no)
        echo "Cancelled as requested."
        return 1
        ;;
      * )
        echo "Please answer 'yes' or 'no'."
        ;;
    esac
    unset answer
  done
}

fatal_missing_var() {
  local var_name="$1"
  if [[ ! -v "${var_name}" ]]; then
    die "Missing mandatory environment variable '\$${var_name}', exiting."
  fi

  local var_value="${!var_name}"
  if [[ -z "${var_value}" ]]; then
    die "Empty mandatory environment variable '\$${var_name}', exiting."
  fi
}

fatal_missing_var FORCE_UPGRADE

tmpfile=$(mktemp)
cleanup() {
  exit_status=$?
  trap '' EXIT HUP INT TERM
  rm -f "${tmpfile}"
  echo
  exit $exit_status
}
trap cleanup EXIT HUP INT TERM

MAIN_PPA_FILE="/etc/apt/sources.list.d/sipwise_ppa.list"
PPA_PREFERENCES_FILE="/etc/apt/preferences.d/00_sipwise_ppa"

if [[ -f "${MAIN_PPA_FILE}" ]] && grep -q '^deb' "${MAIN_PPA_FILE}" ; then
  awk '/^deb/ {print $4}' "${MAIN_PPA_FILE}" &> "${tmpfile}"
fi

if [[ -s "${tmpfile}" ]]; then
  echo
  echo "WARNING: We found the following Sipwise PPAs enabled, which might"
  echo "         interfere with other packages or versions from the main"
  echo "         repositories."
  echo
  echo "These are the Sipwise PPAs in '${MAIN_PPA_FILE}':"
  echo "----------------------------------------"
  cat "${tmpfile}"
  echo "----------------------------------------"
  echo
  echo "And these are their associated apt preferences config files:"
  echo "----------------------------------------"
  cat "${PPA_PREFERENCES_FILE}"
  unset ppa

  echo
  echo "The chances for a successful and fully functional upgrades, including"
  echo "not keeping old versions of packages stuck, are decreased with each"
  echo "additional PPA, specially if the Pin-Priority is higher than that of"
  echo "the main repositories."
  echo
  echo "You can inspect the situation and remove the unnecessary Sipwise PPAs,"
  echo "or at least lower their priority in another terminal, and then continue"
  echo "with the upgrade."
  echo

  request_confirmation
else
  echo "This system doesn't seem to have Sipwise PPAs enabled"
fi
