#!/bin/bash
## TT#8405 Validate YML schema before the upgrade

set -e

if [ -z "${UPGRADE_VERSION}" ] ; then
  echo "ERROR: Missing mandatory environment variable '\$UPGRADE_VERSION', exiting." >&2
  exit 1
fi

if [ -z "${FORCE_UPGRADE}" ] ; then
  echo "ERROR: Missing mandatory environment variable '\$FORCE_UPGRADE', exiting." >&2
  exit 1
fi

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
}

echo "Checking possible YML schema corruption:"
if ngcpcfg --validate check ; then
  echo "All YML configuration files were validated successfully"
else
  echo "WARNING: YML configuration file(s) are invalid, see details above."
  echo "         It is HIGHLY NOT recommended upgrade to ${UPGRADE_VERSION}"
  echo "         having YML config files which doesn't pass validation."
  echo "         mr6.5+ validates all YML config file before using them."
  echo "         Please proceed here if you know what you are doing ONLY!"

  request_confirmation
fi
