#!/bin/bash

COLOR_RED=`tput setaf 1`
COLOR_GREEN=`tput setaf 2`
COLOR_YELLOW=`tput setaf 3`
COLOR_BLUE=`tput setaf 4`
COLOR_MAGENTA=`tput setaf 5`
COLOR_CYAN=`tput setaf 6`

TEXT_BOLD=$(tput bold)
TEXT_DIM=$(tput dim)
TEXT_UNDERLINE=$(tput smul)
TEXT_RESET=$(tput sgr0)

H2_COUNT=0
H3_COUNT=0

function reset_colors() {
  echo -ne "${TEXT_RESET}\033[1K"
}

function echo_h1() {
  echo -e "${TEXT_BOLD}${TEXT_UNDERLINE}${1}${TEXT_RESET}"

  echo -e "${1}" >> $LOGFILE
  echo "===============================================================================" >> $LOGFILE
}

function echo_h2() {
  msg=$1
  prefix=$2

  H2_COUNT=$(($H2_COUNT + 1))
  H3_COUNT=0
  echo
  echo -e "${prefix}${TEXT_UNDERLINE}${H2_COUNT}) ${msg}${TEXT_RESET}"

  echo >> $LOGFILE
  echo -e "${prefix}${H2_COUNT}) ${msg}" >> $LOGFILE
  echo "-------------------------------------------------------------------------------" >> $LOGFILE
}

function echo_h3() {
  msg=$1
  prefix=$2

  H3_COUNT=$(($H3_COUNT + 1))
  echo
  echo -e "${prefix}${TEXT_UNDERLINE}${H2_COUNT}.${H3_COUNT}) ${msg}${TEXT_RESET}"

  echo >> $LOGFILE
  echo -e "${prefix}${H2_COUNT}.${H3_COUNT}) ${msg}" >> $LOGFILE
  echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" >> $LOGFILE
}

function echo_h4() {
  msg=$1
  prefix=$2
  echo -e "${prefix}${TEXT_UNDERLINE}${msg}${TEXT_RESET}"
  echo -e "${prefix}${msg}" >> $LOGFILE
  echo "~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~" >> $LOGFILE
}

function echo_warning() {
  echo -e "${COLOR_RED}$1${TEXT_RESET}"
  echo -e "WARNING: $1" >> $LOGFILE
}

function echo_highlight() {
  echo "${COLOR_CYAN}$1${TEXT_RESET}"
  echo -e "$1" >> $LOGFILE
}

function echo_green() {
  echo "${COLOR_GREEN}$1${TEXT_RESET}"
  echo -e "$1" >> $LOGFILE
}

function echo_blue() {
  echo "${COLOR_BLUE}$1${TEXT_RESET}"
  echo -e "$1" >> $LOGFILE
}

function echo_dim() {
  echo "${TEXT_DIM}$1${TEXT_RESET}"
  echo -e "$1" >> $LOGFILE
}

function echo_reset_dim() {
  echo "${TEXT_RESET}${TEXT_DIM}    $1"
  echo -e "$1" >> $LOGFILE
}

function echo_hr1() {
  echo "===============================================================================" | tee $LOGFILE
}

function echo_hr2() {
  echo "-------------------------------------------------------------------------------" | tee $LOGFILE
}


# Prompt for confirmation to continue
# -----------------------------------------------------------------------------
# Usage:
#  confirm "Do you want to continue" $SAVED_RESPONSE_FROM_LAST_TIME
#  confirm "Do you want to continue"
confirm() {
  prompt=$1
  default=$2
  if [[ "${default}" != "" ]]; then
    read -e -p "${COLOR_YELLOW}${prompt:-Proceed? [y/N]} ${COLOR_MAGENTA}" -i "${default}" response
  else
    read -p "${COLOR_YELLOW}${prompt:-Proceed? [y/N]} ${COLOR_MAGENTA}" response
  fi

  case "$response" in
    [yY][eE][sS]|[yY])
      export ALREADY_CONFIRMED="true"
      true
      ;;
    [nN][oO]|[nN])
      false
      ;;
    *)
      false
      ;;
  esac
}

confirm_default_yes() {
  read -r -p "${COLOR_YELLOW}${1:-Proceed? [Y/n]} ${COLOR_MAGENTA}" response
  case "$response" in
    [yY][eE][sS]|[yY])
      export ALREADY_CONFIRMED="true"
      true
      ;;
    [nN][oO]|[nN])
      export ALREADY_CONFIRMED="true"
      false
      ;;
    *)
      true
      ;;
  esac
}

function prompt_for_number(){
  msg=$1
  varname=$2
  # When override is set, the default provided in $3 will override the saved default
  override=$4

  if [[ -z "${!varname}" || "$override" == "override" ]]; then
    # Use the script default
    default=$3
  else
    # Use the saved default
    default=${!varname}
  fi

  while :; do

    if [[ "${default}" != "" ]]; then
      read -e -p "${COLOR_YELLOW}$msg ${COLOR_MAGENTA}> " -i "${default}" input
    else
      read -p "${COLOR_YELLOW}$msg ${COLOR_MAGENTA}> " input
    fi
    echo -ne "${TEXT_RESET}\033[1K"
    # https://stackoverflow.com/a/13717788
    re='^[1-9][0-9]*$'
    if [[ $input =~ $re ]] ; then
      break
    fi
  done
  printf -v "$varname" "%s" "$input"
}

function prompt_for_secret(){
  msg=$1
  varname=$2
  # When override is set, the default provided in $3 will override the saved default
  reuse_msg=$3

  # Use the saved default
  default=${!varname}

  if [[ "${default}" != "" && "${reuse_msg}" != "" ]]; then
    if ! confirm_default_yes "$reuse_msg [Y/n]"; then
      input=$(/bin/systemd-ask-password "${COLOR_YELLOW}$msg ${COLOR_MAGENTA}> ")
      echo -ne "${TEXT_RESET}\033[1K"
      # https://stackoverflow.com/a/13717788
      printf -v "$varname" "%s" "$input"
    fi
  else
    input=$(/bin/systemd-ask-password "${COLOR_YELLOW}$msg ${COLOR_MAGENTA}> ")
    echo -ne "${TEXT_RESET}\033[1K"
    # https://stackoverflow.com/a/13717788
    printf -v "$varname" "%s" "$input"
  fi
  echo -ne "${TEXT_RESET}\033[1K"
}


function prompt_for_input(){
  msg=$1
  varname=$2
  # When override is set, the default provided in $3 will override the saved default
  override=$4

  if [[ -z "${!varname}" || "$override" == "override" ]]; then
    # Use the script default
    default=$3
  else
    # Use the saved default
    default=${!varname}
  fi

  if [[ "${default}" != "" ]]; then
    read -e -p "${COLOR_YELLOW}$msg ${COLOR_MAGENTA}> " -i "${default}" input
  else
    read -p "${COLOR_YELLOW}$msg ${COLOR_MAGENTA}> " input
  fi
  echo -ne "${TEXT_RESET}\033[1K"
  # https://stackoverflow.com/a/13717788
  printf -v "$varname" "%s" "$input"
}

function check_project_exists(){
  varname=$1
  oc get "project/$varname" > /dev/null 2>&1

  if [ "$?" == "0" ]; then
    true
  else
    false
  fi
}

function prompt_for_confirm() {
  msg=$1
  varname=$2
  if [[ "$varname" != "" ]]; then
    if [[ "${!varname}" == "true" ]]; then
      default="y"
    elif [[ "${!varname}" == "false" ]]; then
      default="n"
    else
      default=""
    fi
  else
    default=""
  fi

  if confirm "${COLOR_YELLOW}$msg ${COLOR_MAGENTA}[y/N]" $default; then
    # Reset colours and clear the current line (\033[1K)
    echo -ne "${TEXT_RESET}\033[1K"
    # Set the variable named "$varname" to "true"
    if [[ "$varname" != "" ]]; then
      printf -v "$varname" "%s" "true"
    fi
    true
  else
    # Reset colours and clear the current line (\033[1K)
    echo -ne "${TEXT_RESET}\033[1K"
    # Set the variable named "$varname" to "false"
    if [[ "$varname" != "" ]]; then
      printf -v "$varname" "%s" "false"
    fi
    false
  fi
}

function prompt_for_confirm_default_yes() {
  msg=$1
  varname=$2
  if confirm_default_yes "${COLOR_YELLOW}$msg ${COLOR_MAGENTA}[Y/n]"; then
    # Reset colours and clear the current line (\033[1K)
    echo -ne "${TEXT_RESET}\033[1K"
    if [[ "$varname" != "" ]]; then
      printf -v "$varname" "%s" "true"
    fi
    true
  else
    # Reset colours and clear the current line (\033[1K)
    echo -ne "${TEXT_RESET}\033[1K"
    if [[ "$varname" != "" ]]; then
      printf -v "$varname" "%s" "false"
    fi
    false
  fi
}

function install_dependencies_ubuntu() {
  # APT package installations
  # python3-pip is required to install additional python packages
  # ansible is required for ansible-galaxy command to be available
  sudo apt install python3-pip ansible

  # Python package installations
  python3 -m pip install ansible junit_xml pymongo xmljson kubernetes==12.0.1 openshift==0.12.1

  # Confirm versions
  python3 --version
  ansible-playbook --version
}

function detect_airgap() {
  oc get ImageContentSourcePolicy ibm-mas-and-dependencies &> /dev/null
  if [[ "$?" == "0" ]]; then
    export AIRGAP_MODE=true
  else
    unset AIRGAP_MODE
  fi
}

# detect_sno function checks the number of nodes in the cluster. If there is only one node, then the cluster is an SNO
# For SNO, we have only one master node and zero worker nodes
# We check for the number of lines the command oc get nodes returns. If it is equal to 2, then the cluster is SNO
# The reason we check for 2 is that the first line is the heading. Following is an example of the output
#                        NAME                           STATUS   ROLES           AGE   VERSION
#                        ip-10-0-141-250.ec2.internal   Ready    master,worker   22h   v1.21.11+5cc9227
# when we run wc -l shell script command, wc gets the word count and -l gets the number of lines.
function detect_sno() {
  sno_num_nodes=$(oc get nodes | wc -l | xargs)
  if [[ "$sno_num_nodes" == "2" ]]; then
    export SNO_MODE=true
  else
    unset SNO_MODE
  fi
}


function ocp_version_check() {
  # TODO: Migrate this into python-devops
  # Check for OCP 4.9, 4.10, & 4.11
  export OCP_VERSION=$(oc get clusterversion version -o jsonpath="{.status.desired.version}")
  if [[ "$OCP_VERSION" =~ ^4\.9\.* ]] || [[ "$OCP_VERSION" =~ ^4\.10\.* ]] || [[ "$OCP_VERSION" =~ ^4\.11\.* ]]; then
    echo
    echo_warning "Warning: OpenShift Container Platform v${OCP_VERSION} detected!"
    echo_warning " - This version is now out of support by Red Hat and ${TEXT_UNDERLINE}not a supported platform for IBM Maximo Application Suite${TEXT_RESET}"
    echo_warning " - The installation of IBM Maximo Application Suite may not proceed, you must upgrade to at least OCP v4.12 before installing/updating/upgrading MAS"
    echo
    echo_warning "For more information refer to the Red Hat OpenShift Container Platform Life Cycle Policy:"
    echo "  ${COLOR_CYAN}${TEXT_UNDERLINE}https://access.redhat.com/support/policy/updates/openshift/${TEXT_RESET}"
    reset_colors
    exit 1
  fi
}

# Calls jinjanate with common arguments. Call jinjanate directly if this does not suit your use case. 
function jinjanate_commmon() {
  local template_path=$1
  local output_path=$2
  local filter_files=$(ls $CLI_DIR/templates/filters/*.py)
  for file in $filter_files; do
    local filter_params="${filter_params} --filters ${file}"
  done
  if [ -n "$output_path" ]; then
    local output_opts="-o ${output_path}"
  fi
  jinjanate --quiet --undefined $filter_params $template_path $output_opts
}
