#!/bin/bash
# To see full description of modifiers go to https://www.gnu.org/software/bash/manual/html_node/The-Set-Builtin.html
# x - print a trace of simple commands, use for debugging, for eg. if var substitution works as expected
# e - exit immediately if a pipeline returns non-zero status
# u - treat unset variables and parameters as an error
# o pipefail - sets the return value of a pipeline to the value of last command with non-zero status, or zero if all are zero

# set -x
set -euo pipefail


usage() {
  echo "Usage: $0 -n SERVICE_NAMESPACE -c KUBERNETES_CONTEXT .env_file " 1>&2
}

main() {
  dotenv $5
  required_env "GITHUB_TOKEN"

  # Config
  SERVICE_NAMESPACE=""
  SERVICE_NAME="policy-service"
  SERVICE_CHART_PATH="sky-generic-secrets"
  KUBE_CONTEXT="" # your kubernetes context for dev, uat and prod clusters
  GITHUB_TOKEN="${GITHUB_TOKEN}"

  # load deploy env
  while getopts "n:c:h" options; do
    case "${options}" in
      n)
      SERVICE_NAMESPACE=${OPTARG}
      ;;
      c)
      KUBE_CONTEXT=${OPTARG}
      ;;
      h)
      usage
      exit 1
      ;;
    esac
  done
  if [[ "$SERVICE_NAMESPACE" = "" || "$KUBE_CONTEXT" == "" ]]; then
    usage
    exit 1
  fi

  {
    cat <<-END
data:

END
  } | helm upgrade --install --wait \
    --username "github-actions[bot]" --password "${GITHUB_TOKEN}" \
    --repo "https://raw.githubusercontent.com/sky-distribution/digital-helmcharts/main/repo/" \
    --kube-context "${KUBE_CONTEXT}" --namespace "${SERVICE_NAMESPACE}" "${SERVICE_NAME}" "${SERVICE_CHART_PATH}" -f -

}

dotenv() {
  local file=$([ -z "$1" ] && echo "../.env" || echo "../.env.$1")
  echo "Using env_file=${file}"
  if [ -f $file ]; then
    set -a
    source $file
    set +a
  fi
}

required_env() {
  local env_names=($1)
  for env_name in $env_names; do
    if [[ -z "${!env_name:-}" ]]; then
      echo "Required ENV Variables: $1 (${env_name})"
      exit 1
    fi
  done
}

# set pwd to current directory
cd "$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"

main $@
