#!/usr/bin/env bash

function gitops_deprovision_cp4d_service_help() {
  [[ -n "$1" ]] && echo_warning "$1"
  reset_colors
  cat << EOM
Usage:
  mas gitops_deprovision_cp4d_service [options]
Where ${COLOR_YELLOW}specified${TEXT_RESET} each option may also be defined by setting the appropriate environment variable.
When no options are specified on the command line, interactive-mode will be enabled by default.

GitOps Configuration:
  -d, --dir ${COLOR_YELLOW}GITOPS_WORKING_DIR${TEXT_RESET}           Directory for GitOps repository
  -a, --account-id ${COLOR_YELLOW}ACCOUNT_ID${TEXT_RESET}            Account name that the cluster belongs to
  -c, --cluster-id ${COLOR_YELLOW}CLUSTER_ID${TEXT_RESET}            Cluster ID
  -r, --region-id ${COLOR_YELLOW}REGION_ID${TEXT_RESET}              Region ID

IBM Maximo Application Suite:
  -m, --mas-instance-id ${COLOR_YELLOW}MAS_INSTANCE_ID${TEXT_RESET}   IBM Suite Maximo Application Suite Instance ID

Secrets Manager:
      --secrets-path ${COLOR_YELLOW}SECRETS_PATH${TEXT_RESET}                    Secrets Manager path
      --secrets-key-seperator ${COLOR_YELLOW}SECRETS_KEY_SEPERATOR${TEXT_RESET}  Secrets Manager key seperator string

IBM CP4D Service:
      --cpd-service-name ${COLOR_YELLOW}CPD_SERVICE_NAME${TEXT_RESET}                                         CP4D Service Name
      --cp4d-wsl-action ${COLOR_YELLOW}CP4D_WSL_ACTION${TEXT_RESET}                                           Whether WSL service to be uninstalled
      --cp4d-watson-machine-learning-action ${COLOR_YELLOW}CP4D_WATSON_MACHINE_LEARNING_ACTION${TEXT_RESET}   Whether WML service to be uninstalled
      --cp4d-spss-modeler-action ${COLOR_YELLOW}CP4D_SPSS_MODELER_ACTION${TEXT_RESET}                         Whether SPSS service to be uninstalled


Automatic GitHub Push:
  -P, --github-push ${COLOR_YELLOW}GITHUB_PUSH${TEXT_RESET}        Enable automatic push to GitHub
  -H, --github-host ${COLOR_YELLOW}GITHUB_HOST${TEXT_RESET}        GitHub Hostname for your GitOps repository
  -O, --github-org  ${COLOR_YELLOW}GITHUB_ORG${TEXT_RESET}         Github org for your GitOps repository
  -R, --github-repo ${COLOR_YELLOW}GITHUB_REPO${TEXT_RESET}        Github repo for your GitOps repository
  -B, --git-branch ${COLOR_YELLOW}GIT_BRANCH${TEXT_RESET}          Git branch to commit to of your GitOps repository
  -M, --git-commit-msg ${COLOR_YELLOW}GIT_COMMIT_MSG${TEXT_RESET}  Git commit message to use when committing to of your GitOps repository
  -S, --github-ssh  ${COLOR_YELLOW}GIT_SSH${TEXT_RESET}            Git ssh key path

Other Commands:
  -h, --help                                      Show this help message
EOM
  [[ -n "$1" ]] && exit 1 || exit 0
}

function gitops_deprovision_cp4d_service_noninteractive() {
  GITOPS_WORKING_DIR=$PWD/working-dir
  SECRETS_KEY_SEPERATOR="/"
  GIT_COMMIT_MSG="gitops-deprovision-cp4d-service commit"

  export REGION_ID=${REGION_ID:-${SM_AWS_REGION}}
  export CPD_SERVICE_INSTALLPLAN_APPROVAL=${CPD_SERVICE_INSTALLPLAN_APPROVAL:-"Automatic"}
  export CPD_CCS_INSTALL_PLAN=${CPD_CCS_INSTALL_PLAN:-"Automatic"}
  export CPD_DATAREFINERY_INSTALL_PLAN=${CPD_DATAREFINERY_INSTALL_PLAN:-"Automatic"}
  export CPD_WS_INSTALL_PLAN=${CPD_WS_INSTALL_PLAN:-"Automatic"}
  export RABBITMQ_INSTALL_PLAN=${RABBITMQ_INSTALL_PLAN:-"Automatic"}
  export ELASTICSEARCH_INSTALL_PLAN=${ELASTICSEARCH_INSTALL_PLAN:-"Automatic"}
  export OPENSEARCH_INSTALL_PLAN=${OPENSEARCH_INSTALL_PLAN:-"Automatic"}
  export CANVASBASE_INSTALL_PLAN=${CANVASBASE_INSTALL_PLAN:-"Automatic"}


  while [[ $# -gt 0 ]]
  do
    key="$1"
    shift
    case $key in
      # GitOps Configuration
      -d|--dir)
        export GITOPS_WORKING_DIR=$1 && shift
        ;;
      -g|--gitops-version)
        echo "${COLOR_YELLOW}WARNING: the -g|--gitops-version parameter is deprecated; it has no effect and will be removed in a future release${COLOR_RESET}"
        shift
        ;;
      -a|--account-id)
        export ACCOUNT_ID=$1 && shift
        ;;
      -c|--cluster-id)
        export CLUSTER_ID=$1 && shift
        ;;
      -r|--region-id)
        export REGION_ID=$1 && shift
        ;;

      # MAS
      -m|--mas-instance-id)
        export MAS_INSTANCE_ID=$1 && shift
        ;;

      # Secrets Manager
      --secrets-path)
        export SECRETS_PATH=$1 && shift
        ;;
      --secrets-key-seperator)
        export SECRETS_KEY_SEPERATOR=$1 && shift
        ;;

      # CP4D Service
      --cpd-service-name)
        export CPD_SERVICE_NAME=$1 && shift
        ;;
      --cp4d-wsl-action)
        export CP4D_WSL_ACTION=$1 && shift
        ;;
      --cp4d-watson-machine-learning-action)
        export CP4D_WATSON_MACHINE_LEARNING_ACTION=$1 && shift
        ;;
      --cp4d-spss-modeler-action)
        export CP4D_SPSS_MODELER_ACTION=$1 && shift
        ;;

      # Automatic GitHub Push
      -P|--github-push)
        export GITHUB_PUSH=true
        ;;
      -H|--github-host)
        export GITHUB_HOST=$1 && shift
        ;;
      -O|--github-org)
        export GITHUB_ORG=$1 && shift
        ;;
      -R|--github-repo)
        export GITHUB_REPO=$1 && shift
        ;;
      -B|--git-branch)
        export GIT_BRANCH=$1 && shift
        ;;
      -M|--git-commit-msg)
        export GIT_COMMIT_MSG=$1 && shift
        ;;
        
      -S|--github-ssh)
        export GIT_SSH=$1 && shift
        ;;

      # Other Commands
      -h|--help)
        gitops_deprovision_cp4d_service_help
        ;;
      *)
        # unknown option
        echo -e "${COLOR_RED}Usage Error: Unsupported option \"${key}\"${COLOR_RESET}\n"
        gitops_deprovision_cp4d_service_help  "Usage Error: Unsupported option \"${key}\" "
        exit 1
        ;;
      esac
  done

  [[ -z "$GITOPS_WORKING_DIR" ]] && gitops_deprovision_cp4d_service_help "GITOPS_WORKING_DIR is not set"
  [[ -z "$ACCOUNT_ID" ]] && gitops_deprovision_cp4d_service_help "ACCOUNT_ID is not set"
  [[ -z "$CLUSTER_ID" ]] && gitops_deprovision_cp4d_service_help "CLUSTER_ID is not set"
  [[ -z "$REGION_ID" ]] && gitops_deprovision_cp4d_service_help "REGION_ID is not set"

  #MAS
  [[ -z "$MAS_INSTANCE_ID" ]] && gitops_deprovision_cp4d_service_help "MAS_INSTANCE_ID is not set"

  [[ -z "$CPD_SERVICE_NAME" ]] && gitops_deprovision_cp4d_service_help "CPD_SERVICE_NAME is not set"

  if [[ "$GITHUB_PUSH" == "true" ]]; then
    [[ -z "$GITHUB_HOST" ]] && gitops_deprovision_cp4d_service_help "GITHUB_HOST is not set"
    [[ -z "$GITHUB_ORG" ]] && gitops_deprovision_cp4d_service_help "GITHUB_ORG is not set"
    [[ -z "$GITHUB_REPO" ]] && gitops_deprovision_cp4d_service_help "GITHUB_REPO is not set"
    [[ -z "$GIT_BRANCH" ]] && gitops_deprovision_cp4d_service_help "GIT_BRANCH is not set"
  fi

}

function gitops_deprovision_cp4d_service() {
  # Take the first parameter off (it will be create-gitops)
  shift
  if [[ $# -gt 0 ]]; then
    gitops_deprovision_cp4d_service_noninteractive "$@"
  else
    echo "Not supported yet"
    exit 1
    gitops_deprovision_cp4d_service_interactive
  fi

  # catch errors
  set -o pipefail
  trap 'echo "[ERROR] Error occurred at $BASH_SOURCE, line $LINENO, exited with $?"; exit 1' ERR

  mkdir -p ${GITOPS_WORKING_DIR}
  GITOPS_INSTANCE_DIR=${GITOPS_WORKING_DIR}/${GITHUB_REPO}/${ACCOUNT_ID}/${CLUSTER_ID}/${MAS_INSTANCE_ID}

  echo
  reset_colors
  echo_h2 "Review Settings"

  echo "${TEXT_DIM}"
  echo_h2 "Target" "    "
  echo_reset_dim "Account ID ............................ ${COLOR_MAGENTA}${ACCOUNT_ID}"
  echo_reset_dim "Cluster ID ............................ ${COLOR_MAGENTA}${CLUSTER_ID}"
  echo_reset_dim "Instance Config Directory ............. ${COLOR_MAGENTA}${GITOPS_INSTANCE_DIR}"
  reset_colors

  echo "${TEXT_DIM}"
  echo_h2 "Secrets Manager" "    "
  echo_reset_dim "Secrets Path .......................... ${COLOR_MAGENTA}${SECRETS_PATH}"
  reset_colors

  echo "${TEXT_DIM}"
  echo_h2 "IBM Maximo Application Suite" "    "
  echo_reset_dim "Instance ID ............................. ${COLOR_MAGENTA}${MAS_INSTANCE_ID}"
  reset_colors

  echo "${TEXT_DIM}"
  echo_h2 "CP4D service" "    "
  echo_reset_dim "CPD Service Name ........................ ${COLOR_MAGENTA}${CPD_SERVICE_NAME}"
  echo_reset_dim "CPD WSL Action .......................... ${COLOR_MAGENTA}${CP4D_WSL_ACTION}"
  echo_reset_dim "CPD WML Action .......................... ${COLOR_MAGENTA}${CP4D_WATSON_MACHINE_LEARNING_ACTION}"
  echo_reset_dim "CPD SPSS Action ......................... ${COLOR_MAGENTA}${CP4D_SPSS_MODELER_ACTION}"
  reset_colors

  echo "${TEXT_DIM}"
  if [[ "$GITHUB_PUSH" == "true" ]]; then
    echo_h2 "GitOps Target" "    "
    echo_reset_dim "Automatic Push ........................ ${COLOR_GREEN}Enabled"
    echo_reset_dim "Working Directory ..................... ${COLOR_MAGENTA}${GITOPS_WORKING_DIR}"
    echo_reset_dim "Host .................................. ${COLOR_MAGENTA}${GITHUB_HOST}"
    echo_reset_dim "Organization .......................... ${COLOR_MAGENTA}${GITHUB_ORG}"
    echo_reset_dim "Repository ............................ ${COLOR_MAGENTA}${GITHUB_REPO}"
    echo_reset_dim "Branch ................................ ${COLOR_MAGENTA}${GIT_BRANCH}"
  else
    echo_h2 "GitOps Target" "    "
    echo_reset_dim "Automatic Push ........................ ${COLOR_RED}Disabled"
    echo_reset_dim "Working Directory ..................... ${COLOR_MAGENTA}${GITOPS_WORKING_DIR}"
  fi
  reset_colors

  GIT_LOCK_BRANCH=$(git_lock_branch_name "gitops-deprovision-cp4d-service" "${ACCOUNT_ID}" "${CLUSTER_ID}" "${MAS_INSTANCE_ID}")
  CURRENT_DIR=$PWD
  CPD_SERVICE_LIST=(wsl wml spss spark)

  if [ -z $GIT_SSH ]; then
    export GIT_SSH=false
  fi

  # Clone github target repo
  # ---------------------------------------------------------------------------
  if [ "$GITHUB_PUSH" == "true" ]; then
    # only create the lock branch if we plan to actually push changes to git
    clone_and_lock_target_git_repo  "${GITHUB_HOST}" "${GITHUB_ORG}" "${GITHUB_REPO}" "${GIT_BRANCH}" "${GITOPS_WORKING_DIR}" "${GIT_SSH}" "${GIT_LOCK_BRANCH}"
  fi
  mkdir -p ${GITOPS_INSTANCE_DIR}

   echo
  echo_h2 "Deleting CPD Service (${CPD_SERVICE_NAME}) Application"

  if [[ ("$CPD_SERVICE_NAME" == "all") || ("$CP4D_WSL_ACTION" == "uninstall" && "$CP4D_WATSON_MACHINE_LEARNING_ACTION" == "uninstall" && "$CP4D_SPSS_MODELER_ACTION" == "uninstall") ]]; then
    echo "Deleting IBM CPD Service file ${GITOPS_INSTANCE_DIR}/ibm-cp4d-services-base.yaml"
    rm -rf ${GITOPS_INSTANCE_DIR}/ibm-cp4d-services-base.yaml
  fi
  
  if [[ "$CPD_SERVICE_NAME" == "all" ]]; then
    for CPD_SERVICE in "${CPD_SERVICE_LIST[@]}"
    do
      echo "Deleting IBM CPD Service file ${GITOPS_INSTANCE_DIR}/ibm-${CPD_SERVICE}.yaml"
      rm -rf ${GITOPS_INSTANCE_DIR}/ibm-${CPD_SERVICE}.yaml
    done
  else
    echo
    echo "- ${CPD_SERVICE_NAME} operator"

    echo "Deleting IBM CPD Service file ${GITOPS_INSTANCE_DIR}/ibm-${CPD_SERVICE_NAME}.yaml"
    rm -rf ${GITOPS_INSTANCE_DIR}/ibm-${CPD_SERVICE_NAME}.yaml
  fi

  # Commit and push to github target repo
  # ---------------------------------------------------------------------------
  if [ "$GITHUB_PUSH" == "true" ]; then
    echo
    echo_h2 "Commit and push changes to GitHub repo $GITHUB_ORG $GITHUB_REPO"
    save_and_unlock_target_git_repo "${GITHUB_REPO}" "${GIT_BRANCH}" "${GITOPS_WORKING_DIR}" "${GIT_COMMIT_MSG}" "${GIT_LOCK_BRANCH}" CP4D_SERVICE_CHANGED
    remove_git_repo_clone $GITOPS_WORKING_DIR/$GITHUB_REPO
  fi
}