#!/usr/bin/env bash

function gitops_dro_help() {
  [[ -n "$1" ]] && echo_warning "$1"
  reset_colors
  cat << EOM
Usage:
  mas gitops_dro [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.

Basic 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

IBM DRO (Required):
      --dro-namespace ${COLOR_YELLOW}DRO_NAMESPACE${TEXT_RESET}    Namespace to install DRO subscription (defaults to 'ibm-software-central')

IBM CMM Integration (Optional):
      --dro-cmm-setup ${COLOR_YELLOW}DRO_CMM_SETUP${TEXT_RESET}                Set to indicate if we should setup DRO to CMM Integration or not
      --dro-cmm-auth-apikey ${COLOR_YELLOW}DRO_CMM_AUTH_APIKEY${TEXT_RESET}    The API Key used to connect to MCSP
      --dro-cmm-auth-url ${COLOR_YELLOW}DRO_CMM_AUTH_URL${TEXT_RESET}       The MCSP Auth url to obtain the token using the API key
      --dro-cmm-cmm-url ${COLOR_YELLOW}DRO_CMM_CMM_URL${TEXT_RESET}        The MCSP CMM endpoint that DRO will call

AWS Secrets Manager Configuration (Required):
      --sm-aws-secret-region ${COLOR_YELLOW}SM_AWS_REGION${TEXT_RESET}          Region of the AWS Secrets Manager to use
      --sm-aws-access-key ${COLOR_YELLOW}SM_AWS_ACCESS_KEY_ID${TEXT_RESET}      Your AWS Access Key ID
      --sm-aws-secret-key ${COLOR_YELLOW}SM_AWS_SECRET_ACCESS_KEY${TEXT_RESET}  Your AWS Secret Key
      --secrets-path ${COLOR_YELLOW}SECRETS_PATH${TEXT_RESET}                   Secrets Manager path

IBM DRO & IMO Config (Optional):
      --dro-install-plan ${COLOR_YELLOW}DRO_INSTALL_PLAN${TEXT_RESET} DRO subscription install plan approval('Automatic' or 'Manual'. Default is 'Automatic')
      --imo-install-plan ${COLOR_YELLOW}IMO_INSTALL_PLAN${TEXT_RESET} IMO subscription install plan approval('Automatic' or 'Manual'. Default is 'Automatic')

Automatic GitHub Push (Optional):
  -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
  -S, --github-ssh ${COLOR_YELLOW}GIT_SSH${TEXT_RESET}             Git ssh key path
  -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

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

function gitops_dro_noninteractive() {
  GITOPS_WORKING_DIR=$PWD/working-dir
  SECRETS_KEY_SEPERATOR="/"
  GIT_COMMIT_MSG="gitops-dro commit"
  export REGION_ID=${REGION_ID:-${SM_AWS_REGION}}

  export DRO_NAMESPACE=${DRO_NAMESPACE:-"ibm-software-central"}
  export DRO_INSTALL_PLAN=${DRO_INSTALL_PLAN:-"Automatic"}
  export IMO_INSTALL_PLAN=${IMO_INSTALL_PLAN:-"Automatic"}

  while [[ $# -gt 0 ]]
  do
    key="$1"
    shift
    case $key in
      # GitOps Configuration
      -d|--dir)
        export GITOPS_WORKING_DIR=$1 && shift
        ;;
      -a|--account-id)
        export ACCOUNT_ID=$1 && shift
        ;;
      -c|--cluster-id)
        export CLUSTER_ID=$1 && shift
        ;;

      # AWS Secrets Manager Configuration
      --sm-aws-secret-region)
        export SM_AWS_REGION=$1
        export REGION_ID=$1
        shift
        ;;
      --sm-aws-access-key)
        export SM_AWS_ACCESS_KEY_ID=$1 && shift
        ;;
      --sm-aws-secret-key)
        export SM_AWS_SECRET_ACCESS_KEY=$1 && shift
        ;;
      --secrets-path)
        export SECRETS_PATH=$1 && shift
        ;;

      # DRO
      --dro-namespace)
      export DRO_NAMESPACE=$1 && shift
        ;;

      # DRO-CMM
      --dro-cmm-setup)
      export DRO_CMM_SETUP=true
        ;;
      --dro-cmm-auth-apikey)
      export DRO_CMM_AUTH_APIKEY=$1 && shift
        ;;
      --dro-cmm-auth-url)
      export DRO_CMM_AUTH_URL=$1 && shift
        ;;
      --dro-cmm-cmm-url)
      export DRO_CMM_CMM_URL=$1 && shift
        ;;

      # DRO & IMO Config
      --dro-install-plan)
      export DRO_INSTALL_PLAN=$1 && shift
        ;;
      --imo-install-plan)
      export IMO_INSTALL_PLAN=$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
        ;;
      -S|--github-ssh)
        export GIT_SSH=$1 && shift
        ;;
      -B|--git-branch)
        export GIT_BRANCH=$1 && shift
        ;;
      -M|--git-commit-msg)
        export GIT_COMMIT_MSG=$1 && shift
        ;;

      # Other Commands
      -h|--help)
        gitops_dro_help
        ;;
      *)
        # unknown option
        gitops_dro_help  "Usage Error: Unsupported option \"${key}\" "
        ;;
      esac
  done

  [[ -z "$GITOPS_WORKING_DIR" ]] && gitops_dro_help "GITOPS_WORKING_DIR is not set"
  [[ -z "$ACCOUNT_ID" ]] && gitops_dro_help "ACCOUNT_ID is not set"
  [[ -z "$CLUSTER_ID" ]] && gitops_dro_help "CLUSTER_ID is not set"
  [[ -z "$REGION_ID" && -z "$SM_AWS_REGION" ]] && gitops_dro_help "REGION_ID or SM_AWS_REGION is not set"

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

  if [[ "$DRO_CMM_SETUP" == "true" ]]; then
    [[ -z "$DRO_CMM_AUTH_APIKEY" ]] && gitops_dro_help "DRO_CMM_AUTH_APIKEY is not set"
    [[ -z "$DRO_CMM_AUTH_URL" ]] && gitops_dro_help "DRO_CMM_AUTH_URL is not set"
    [[ -z "$DRO_CMM_CMM_URL" ]] && gitops_dro_help "DRO_CMM_CMM_URL is not set"
  fi
}

function gitops_dro() {
  # Take the first parameter off (it will be create-gitops)
  shift
  if [[ $# -gt 0 ]]; then
    gitops_dro_noninteractive "$@"
  else
    echo "Not supported yet"
    exit 1
    gitops_dro_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_CLUSTER_DIR=${GITOPS_WORKING_DIR}/${GITHUB_REPO}/${ACCOUNT_ID}/${CLUSTER_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 "Region ID ...................... ${COLOR_MAGENTA}${REGION_ID}"
  echo_reset_dim "Cluster ID ..................... ${COLOR_MAGENTA}${CLUSTER_ID}"
  echo_reset_dim "Cluster Config Directory ....... ${COLOR_MAGENTA}${GITOPS_CLUSTER_DIR}"
  reset_colors

  echo "${TEXT_DIM}"
  echo_h2 "AWS Secrets Manager" "    "
  echo_reset_dim "Region ......................... ${COLOR_MAGENTA}${SM_AWS_REGION}"
  echo_reset_dim "Secret Key ..................... ${COLOR_MAGENTA}${SM_AWS_ACCESS_KEY_ID:0:4}<snip>"
  echo_reset_dim "Access Key ..................... ${COLOR_MAGENTA}${SM_AWS_SECRET_ACCESS_KEY:0:4}<snip>"
  echo_reset_dim "Secrets Path ................... ${COLOR_MAGENTA}${SECRETS_PATH}"
  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

  echo "${TEXT_DIM}"
  echo_h2 "DRO Operator" "    "
  echo_reset_dim "DRO_NAMESPACE  .......................... ${COLOR_MAGENTA}${DRO_NAMESPACE}"
  reset_colors

  echo "${TEXT_DIM}"
  echo_h2 "DRO CMM Integration" "    "
  echo_reset_dim "DRO_CMM_SETUP  .......................... ${COLOR_MAGENTA}${DRO_CMM_SETUP}"
  echo_reset_dim "DRO_CMM_AUTH_APIKEY  .................... ${COLOR_MAGENTA}${DRO_CMM_AUTH_APIKEY:0:4}<snip>"
  echo_reset_dim "DRO_CMM_AUTH_URL  ....................... ${COLOR_MAGENTA}${DRO_CMM_AUTH_URL}"
  echo_reset_dim "DRO_CMM_CMM_URL  ........................ ${COLOR_MAGENTA}${DRO_CMM_CMM_URL}"
  reset_colors

  # Set up secrets
  # ---------------------------------------------------------------------------
  CURRENT_DIR=$PWD
  TEMP_DIR=$CURRENT_DIR/tmp-dro
  mkdir -p $TEMP_DIR
  AVP_TYPE=aws
  sm_login

  # Define cluster-level secrets used
  # ---------------------------------------------------------------------------
  # Note that SECRET_KEY_IBM_ENTITLEMENT cluster-level secret is set up by gitops-cluster
  export SECRET_KEY_IBM_ENTITLEMENT=${ACCOUNT_ID}${SECRETS_KEY_SEPERATOR}${CLUSTER_ID}${SECRETS_KEY_SEPERATOR}ibm_entitlement#entitlement_key
  
  if [ "$DRO_CMM_SETUP" == "true" ]; then
    export SECRET_KEY_DRO_CMM_AUTH_APIKEY=${ACCOUNT_ID}${SECRETS_KEY_SEPERATOR}${CLUSTER_ID}${SECRETS_KEY_SEPERATOR}dro_cmm_auth#api_key
    export SECRET_NAME_DRO_CMM_AUTH=${ACCOUNT_ID}${SECRETS_KEY_SEPERATOR}${CLUSTER_ID}${SECRETS_KEY_SEPERATOR}dro_cmm_auth
    TAGS="[{\"Key\": \"source\", \"Value\": \"gitops_dro\"}, {\"Key\": \"account\", \"Value\": \"${ACCOUNT_ID}\"}, {\"Key\": \"cluster\", \"Value\": \"${CLUSTER_ID}\"}]"
    sm_update_secret $SECRET_NAME_DRO_CMM_AUTH "{\"api_key\": \"$DRO_CMM_AUTH_APIKEY\"}" "${TAGS}"
  fi

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


  # Set and Validate App Names
  # ---------------------------------------------------------------------------
  ROOT_APP_NAME="root.${ACCOUNT_ID}"
  CLUSTER_APP_NAME="cluster.${CLUSTER_ID}"
  DRO_APP_NAME="dro.${CLUSTER_ID}"

  validate_app_name "${ROOT_APP_NAME}"
  validate_app_name "${CLUSTER_APP_NAME}"
  validate_app_name "${DRO_APP_NAME}"


  # Clone github target repo
  # ---------------------------------------------------------------------------
  if [ "$GITHUB_PUSH" == "true" ]; then
    echo
    echo_h2 "Cloning GitHub repo $GITHUB_ORG $GITHUB_REPO"
    clone_target_git_repo $GITHUB_HOST $GITHUB_ORG $GITHUB_REPO $GIT_BRANCH $GITOPS_WORKING_DIR $GIT_SSH
  fi
  mkdir -p ${GITOPS_CLUSTER_DIR}


  # Generate ArgoApps
  # ---------------------------------------------------------------------------
  echo
  echo_h2 "Generating dro operator Applications"
  echo "- dro operator"

  export IBM_ENTITLEMENT_KEY=$SECRET_KEY_IBM_ENTITLEMENT

  echo "Generating dro file ${GITOPS_CLUSTER_DIR}/ibm-dro.yaml"
  jinjanate_commmon $CLI_DIR/templates/gitops/appset-configs/cluster/ibm-dro.yaml.j2 ${GITOPS_CLUSTER_DIR}/ibm-dro.yaml

  # 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_to_target_git_repo $GITHUB_HOST $GITHUB_ORG $GITHUB_REPO $GIT_BRANCH "${GITOPS_WORKING_DIR}/${GITHUB_REPO}" "${GIT_COMMIT_MSG}"
    remove_git_repo_clone $GITOPS_WORKING_DIR/$GITHUB_REPO
  fi

  # Get generated DRO API Token and set it in AWS SM
  # ---------------------------------------------------------------------------
  # This is now handled by a postsync job in the ibm-dro chart

  rm -rf $TEMP_DIR

}
