#!/usr/bin/env bash
set -euo pipefail

ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)
env_file=${1:-"$ROOT/.env"}

if [[ "$env_file" != /* ]]; then
  env_file="$ROOT/$env_file"
fi

if [[ ! -f "$env_file" ]]; then
  echo "Deployment environment does not exist: $env_file" >&2
  exit 1
fi

read_env_value() {
  local key=$1

  awk -v key="$key" '
    index($0, key "=") == 1 {
      print substr($0, length(key) + 2)
      found = 1
      exit
    }
    END { if (!found) exit 1 }
  ' "$env_file"
}

deployment_target=$(read_env_value DEPLOYMENT_TARGET 2>/dev/null || printf compose)
database_mode=$(read_env_value DATABASE_MODE 2>/dev/null || printf container)

case "$deployment_target" in
  compose)
    exec "$ROOT/scripts/compose-up.sh" "$env_file"
    ;;

  kubernetes)
    kubernetes_mode=$(read_env_value KUBERNETES_MODE 2>/dev/null || true)
    case "${kubernetes_mode:-kind}" in
      kind)
        [[ "$database_mode" == container ]] || {
          echo "The project-owned kind drill requires DATABASE_MODE=container." >&2
          exit 1
        }
        exec "$ROOT/scripts/kind-up.sh"
        ;;

      helm)
        [[ "$database_mode" == external ]] || {
          echo "A production Helm deployment requires DATABASE_MODE=external." >&2
          exit 1
        }
        KUBE_CONTEXT=$(read_env_value KUBE_CONTEXT 2>/dev/null || true)
        KUBE_NAMESPACE=$(read_env_value KUBE_NAMESPACE 2>/dev/null || true)
        KUBE_RELEASE=$(read_env_value KUBE_RELEASE 2>/dev/null || true)
        KUBE_VALUES_FILE=$(read_env_value KUBE_VALUES_FILE 2>/dev/null || true)
        : "${KUBE_CONTEXT:?Set KUBE_CONTEXT for KUBERNETES_MODE=helm}"
        : "${KUBE_NAMESPACE:?Set KUBE_NAMESPACE for KUBERNETES_MODE=helm}"
        : "${KUBE_RELEASE:?Set KUBE_RELEASE for KUBERNETES_MODE=helm}"
        : "${KUBE_VALUES_FILE:?Set KUBE_VALUES_FILE for KUBERNETES_MODE=helm}"
        if [[ "$KUBE_VALUES_FILE" != /* ]]; then
          KUBE_VALUES_FILE="$ROOT/$KUBE_VALUES_FILE"
        fi
        [[ -f "$KUBE_VALUES_FILE" ]] || {
          echo "KUBE_VALUES_FILE does not exist: $KUBE_VALUES_FILE" >&2
          exit 1
        }
        "$ROOT/scripts/bootstrap-kubernetes-tools.sh"
        exec "$ROOT/.tools/bin/helm" upgrade --install "$KUBE_RELEASE" \
          "$ROOT/deploy/helm/who-need-help" \
          --kube-context "$KUBE_CONTEXT" \
          --namespace "$KUBE_NAMESPACE" \
          --values "$KUBE_VALUES_FILE" \
          --wait
        ;;

      *)
        echo "KUBERNETES_MODE must be kind or helm." >&2
        exit 1
        ;;
    esac
    ;;

  *)
    echo "DEPLOYMENT_TARGET must be compose or kubernetes." >&2
    exit 1
    ;;
esac
