#!/bin/bash
# mr5.4: inform users to enable maintenance mode

set -e

### Mandatory environment variables
: "${FORCE_UPGRADE?ERROR: Missing mandatory environment variable 'FORCE_UPGRADE', cannot continue.}"

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 continue here? (yes/no): "
    read -r a
    case "${a,,}" in
      yes)
        echo "Continue as requested."
        break
        ;;
      no)
        echo "Aborted as requested." >&2
        exit 1
        ;;
      *)
        echo "Please answer 'yes' or 'no'."
        ;;
    esac
    unset a
  done
}

get_maintenance_mode_legacy() {
  echo "NGCP_MAINTENANCE is not available in /etc/default/ngcp-roles for mr4.5 LTS, using legacy mode"

  # we cannot use 'ngcpcfg values general.maintenance' here as second+ node cannot read yaml files
  # due to YAML->YAML::XS migration in mr5.4 (ngcpcfg shared storage has new format already)
  mode=$(awk '/maintenance: / {print $NF}' /etc/ngcp-config/config.yml)

  if [ "${mode}" = "yes" ]; then
    echo "Maintenance mode is enabled, continue"
    NGCP_MAINTENANCE=true
  else
    echo "Maintenance mode is NOT enabled, check: awk '/maintenance: / {print \$NF}' /etc/ngcp-config/config.yml"
    NGCP_MAINTENANCE=false
  fi
}

NGCP_MAINTENANCE=""

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

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

if [ -z "${NGCP_MAINTENANCE}" ]; then
  get_maintenance_mode_legacy
fi

if "${NGCP_MAINTENANCE}" ; then
  echo "OK: maintenance mode is enabled"
else
  echo "WARNING: maintenance mode is disabled in config.yml"
  echo "(maintenance mode must be enabled during the upgrade)"
  request_confirmation
fi

