#!/usr/bin/env bash

set -Eeuo pipefail
trap cleanup SIGINT SIGTERM ERR EXIT

script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" &>/dev/null && pwd -P)

# We need to track what we are converting for the dry run - centos, alma or smth else
TMPL=centos-8

usage() {
  cat <<EOF
Usage: $(basename "${BASH_SOURCE[0]}") [-h] [-v] [-f] -p ct_id_value arg1 [arg2...]

Script description here.

Available options:

-h, --help      Print this help and exit
-v, --verbose   Print script debug info
-p, --ct_id     Some ct_id description
-n, --nonetwork  Use only if network not available
EOF
  exit
}

cleanup() {
  trap - SIGINT SIGTERM ERR EXIT
  # script cleanup here
}

setup_colors() {
  if [[ -t 2 ]] && [[ -z "${NO_COLOR-}" ]] && [[ "${TERM-}" != "dumb" ]]; then
    NOFORMAT='\033[0m' RED='\033[0;31m' GREEN='\033[0;32m' ORANGE='\033[0;33m' BLUE='\033[0;34m' PURPLE='\033[0;35m' CYAN='\033[0;36m' YELLOW='\033[1;33m'
  else
    NOFORMAT='' RED='' GREEN='' ORANGE='' BLUE='' PURPLE='' CYAN='' YELLOW=''
  fi
}

msg() {
  echo >&2 -e "${1-}"
}

die() {
  local msg=$1
  local code=${2-1} # default exit status 1
  msg "$msg"
  exit "$code"
}


parse_params() {
  # default values of variables set from params
  ct_id=''
  nonetwork=0
  dryrun=0
  debug=1
  quiet=''
  verbose=''

  while :; do
    case "${1-}" in
    -h | --help) usage ;;
    -v | --verbose) debug=5; verbose='--verbose'; set -x ;;
    --no-color) NO_COLOR=1 ;;
    -n | --nonetwork) nonetwork=1 ;; # flag
    -d | --dry-run) dryrun=1 ;; # flag
    -q | --quiet) quiet='--quiet' ;; # flag
    -c | --ct_id) # container id
      ct_id="${2-}"
      shift
      ;;
    -?*) die "Unknown option: $1" ;;
    *) break ;;
    esac
    shift
  done

  # check required params and arguments
  [[ -z "${ct_id-}" ]] && die "Missing required parameter: --ct_id"

  return 0
}

change_distro() {
CT_PRIV=`cat /etc/vz/vz.conf | grep '^VE_PRIVATE=' | sed 's/VE_PRIVATE=//' | sed 's/"//g' | sed "s/'//g" | sed 's/$VEID//g' `
CT_VE="${CT_PRIV}${ct_id}/ve.conf"
if [ -f "${CT_VE}" ]; then
    grep -q almalinux "${CT_VE}" && TMPL=almalinux-8
    grep -q rockylinux "${CT_VE}" && TMPL=rockylinux-8
    grep -q centos-8.stream "${CT_VE}" && TMPL=centos-8.stream
    # Both centos stream and centos are converted to stable vzlinux
    sed -i 's!centos-8.stream!vzlinux-8!g' "${CT_VE}"
    sed -i 's!centos-8!vzlinux-8!g' "${CT_VE}"
    sed -i 's!almalinux-8!vzlinux-8!g' "${CT_VE}"
    sed -i 's!rockylinux-8!vzlinux-8!g' "${CT_VE}"
else 
    echo "${CT_VE} config does not exist. Exiting"
    exit;
fi

}


parse_params "$@"
setup_colors

# script logic here
run_script() {
if [ ${dryrun} -eq "1" ]; then
	change_distro
	vzpkg update $quiet -d $debug --check-only "${ct_id}"
	if [ $? -eq 0 ]; then
		echo "Upgrade is possible"
	fi
        CT_PRIV=`cat /etc/vz/vz.conf | grep '^VE_PRIVATE=' | sed 's/VE_PRIVATE=//' | sed 's/"//g' | sed "s/'//g" | sed 's/$VEID//g' `
	sed -i "s!vzlinux-8!${TMPL}!g" "${CT_PRIV}${ct_id}/ve.conf"
	exit;
fi
if [ ${nonetwork} -eq "1" ]; then
	change_distro
	vzpkg update $quiet -d $debug "${ct_id}"
  if [ "${TMPL}" = "rockylinux-8"]; then
    vzpkg remove -p -f $quiet -d $debug "${ct_id}" rocky-release rocky-repos
  fi
  if [ "${TMPL}" = "almalinux-8"]; then
    vzpkg remove -p -f $quiet -d $debug "${ct_id}" almalinux-release 
  fi
  if [ "${TMPL}" = "centos-8.stream" ]; then
    vzpkg remove -p -f $quiet -d $debug "${ct_id}" centos-stream-release
    vzpkg remove -p -f $quiet -d $debug "${ct_id}" centos-stream-repos
  fi
  vzpkg install -p -f $quiet -d $debug "${ct_id}" vzlinux-release
else
	vzctl $quiet $verbose runscript "${ct_id}" /usr/bin/vzdeploy8
fi

}

if [[ $verbose == '--verbose' ]]; then
    msg "${RED}INFO:${NOFORMAT}"
    msg "- container id: ${ct_id}"
    msg "- networking: ${nonetwork}"
fi
run_script

