#!/usr/bin/env bash

function gitops_nvidia_gpu_help() {
  [[ -n "$1" ]] && echo_warning "$1"
  reset_colors
  cat << EOM
Usage:
  mas gitops-nvidia-gpu [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
  -r, --region ${COLOR_YELLOW}REGION${TEXT_RESET}                    Region
  -c, --cluster-id ${COLOR_YELLOW}CLUSTER_ID${TEXT_RESET}            Cluster 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

NVIDIA GPU OPERATOR:
      --nfd-namespace ${COLOR_YELLOW}NFD_NAMESPACE${TEXT_RESET}                                 NFD Namespace, defaults to openshift-nfd
      --nfd-channel ${COLOR_YELLOW}NFD_CHANNEL${TEXT_RESET}                                     NFD Channel, defaults to stable
      --nfd-install-plan ${COLOR_YELLOW}NFD_INSTALL_PLAN${TEXT_RESET}                           NFD Subscription install plan, ('Automatic' or 'Manual'. Default is 'Automatic')
      --nfd-image ${COLOR_YELLOW}NFD_IMAGE${TEXT_RESET}                                         NFD Image for worker nodes, default is for ocp version 4.17 and up. Set if ocp version is below 4.17
      --gpu-namespace ${COLOR_YELLOW}GPU_NAMESPACE${TEXT_RESET}                                 GPU Namespace, defaults to nvidia-gpu-operator
      --gpu-channel ${COLOR_YELLOW}GPU_CHANNEL${TEXT_RESET}                                     GPU Channel, defaults to v24.3
      --gpu-install-plan ${COLOR_YELLOW}GPU_INSTALL_PLAN${TEXT_RESET}                           GPU Subscription install plan, ('Automatic' or 'Manual'. Default is 'Automatic')
      --gpu-driver-version ${COLOR_YELLOW}GPU_DRIVER_VERSION${TEXT_RESET}                       GPU Driver Version, defaults to 575.57.08
      --gpu-driver-repository-path ${COLOR_YELLOW}GPU_DRIVER_REPOSITORY_PATH${TEXT_RESET}       GPU Driver Repository, defaults to nvcr.io/nvidia

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_nvidia_gpu_noninteractive() {
  GITOPS_WORKING_DIR=$PWD/working-dir
  SECRETS_KEY_SEPERATOR="/"
  GIT_COMMIT_MSG="gitops-nvidia-gpu commit"

  # defaults for fvtsaas
  # TODO: will need to add explicit args to pipeline when we start using this code to deploy to MCSP
  export REGION=${REGION:-${SM_AWS_REGION}}
  export NFD_INSTALL_PLAN=${NFD_INSTALL_PLAN:-"Automatic"}
  export GPU_INSTALL_PLAN=${GPU_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
        ;;
      -r|--region)
        export REGION=$1 && shift
        ;;
      -c|--cluster-id)
        export CLUSTER_ID=$1 && shift
        ;;

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

      # NVIDIA GPU OPERATOR
      --nfd-namespace)
        export NFD_NAMESPACE=$1 && shift
        ;;
      --nfd-channel)
        export NFD_CHANNEL=$1 && shift
        ;;
      --nfd-install-plan)
        export NFD_INSTALL_PLAN=$1 && shift
        ;;
      --gpu-namespace)
        export GPU_NAMESPACE=$1 && shift
        ;;
      --gpu-channel)
        export GPU_CHANNEL=$1 && shift
        ;;
      --gpu-install-plan)
        export GPU_INSTALL_PLAN=$1 && shift
        ;;
      --gpu-driver-version)
        export GPU_DRIVER_VERSION=$1 && shift
        ;;
      --gpu-driver-repository-path)
        export GPU_DRIVER_REPOSITORY_PATH=$1 && shift
        ;;
      --nfd_image)
        export NFD_IMAGE=$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_nvidia_gpu_help
        ;;
      *)
        # unknown option
        echo -e "${COLOR_RED}Usage Error: Unsupported option \"${key}\"${COLOR_RESET}\n"
        gitops_nvidia_gpu_help  "Usage Error: Unsupported option \"${key}\" "
        exit 1
        ;;
    esac
  done

  [[ -z "$GITOPS_WORKING_DIR" ]] && gitops_nvidia_gpu_help "GITOPS_WORKING_DIR is not set"
  [[ -z "$ACCOUNT_ID" ]] && gitops_nvidia_gpu_help "ACCOUNT_ID is not set"
  [[ -z "$REGION" ]] && gitops_nvidia_gpu_help "REGION is not set"
  [[ -z "$CLUSTER_ID" ]] && gitops_nvidia_gpu_help "CLUSTER_ID is not set"

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

}

function gitops_nvidia_gpu() {
  # Take the first parameter off (it will be create-gitops)
  shift
  if [[ $# -gt 0 ]]; then
    gitops_nvidia_gpu_noninteractive "$@"
  else
    echo "Not supported yet"
    exit 1
    gitops_nvidia_gpu_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 ................................ ${COLOR_MAGENTA}${REGION}"
  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 "Secrets Manager" "    "
  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

  # set default values of envs if not provided
  if [[ -z "${NFD_NAMESPACE}" ]]; then
    export NFD_NAMESPACE=openshift-nfd
  fi
  if [[ -z "${NFD_CHANNEL}" ]]; then
    export NFD_CHANNEL=stable
  fi
  if [[ -z "${GPU_NAMESPACE}" ]]; then
    export GPU_NAMESPACE=nvidia-gpu-operator
  fi
  if [[ -z "${GPU_CHANNEL}" ]]; then
    export GPU_CHANNEL=v24.3
  fi
  if [[ -z "${GPU_DRIVER_VERSION}" ]]; then
    export GPU_DRIVER_VERSION="575.57.08"
  fi
  if [[ -z "${GPU_DRIVER_REPOSITORY_PATH}" ]]; then
    export GPU_DRIVER_REPOSITORY_PATH=nvcr.io/nvidia
  fi
  if [[ -z "${NFD_IMAGE}" ]]; then
    export NFD_IMAGE="registry.redhat.io/openshift4/ose-node-feature-discovery-rhel9@sha256:45192fef5a1250ee573975ced1e897662116d5a30a1f8f4baa4497f64933fba3"
  fi


  echo "${TEXT_DIM}"
  echo_h2 "Nvidia GPU Operator" "    "
  echo_reset_dim "NFD_NAMESPACE ............................. ${COLOR_MAGENTA}${NFD_NAMESPACE}"
  echo_reset_dim "NFD_CHANNEL ............................... ${COLOR_MAGENTA}${NFD_CHANNEL}"
  echo_reset_dim "NFD_INSTALL_PLAN .......................... ${COLOR_MAGENTA}${NFD_INSTALL_PLAN}"
  echo_reset_dim "NFD_IMAGE ................................. ${COLOR_MAGENTA}${NFD_IMAGE}"
  echo_reset_dim "GPU_NAMESPACE ............................. ${COLOR_MAGENTA}${GPU_NAMESPACE}"
  echo_reset_dim "GPU_CHANNEL ............................... ${COLOR_MAGENTA}${GPU_CHANNEL}"
  echo_reset_dim "GPU_INSTALL_PLAN .......................... ${COLOR_MAGENTA}${GPU_INSTALL_PLAN}"
  echo_reset_dim "GPU_DRIVER_VERSION ........................ ${COLOR_MAGENTA}${GPU_DRIVER_VERSION}"
  echo_reset_dim "GPU_DRIVER_REPOSITORY_PATH ................ ${COLOR_MAGENTA}${GPU_DRIVER_REPOSITORY_PATH}"
  reset_colors

  CURRENT_DIR=$PWD
  TEMP_DIR=$CURRENT_DIR/tmp-gpu
  mkdir -p $TEMP_DIR

  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}"
  NVIDIA_GPU_APP_NAME="nvidia-gpu.${CLUSTER_ID}"

  validate_app_name "${ROOT_APP_NAME}"
  validate_app_name "${CLUSTER_APP_NAME}"
  validate_app_name "${NVIDIA_GPU_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 Nvidia GPU Operator Applications"
  echo "- Nvidia GPU Operator"

  echo "Generating Nvidia GPU operator file ${GITOPS_CLUSTER_DIR}/nvidia-gpu-operator.yaml"
  jinjanate_commmon $CLI_DIR/templates/gitops/appset-configs/cluster/nvidia-gpu-operator.yaml.j2 ${GITOPS_CLUSTER_DIR}/nvidia-gpu-operator.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

  rm -rf $TEMP_DIR

}
