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

OPENBAO_NAMESPACE="${OPENBAO_NAMESPACE:-openbao}"
KUBECTL="${KUBECTL:-kubectl}"
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
OVERLAY_DIR="${OPENBAO_UI_OVERLAY_DIR:-$ROOT_DIR/helm/openbao-ui-overlay}"
K8S_MANIFEST="${OPENBAO_UI_OVERLAY_K8S:-$ROOT_DIR/helm/openbao-ui-overlay-k8s.yaml}"

usage() {
  cat <<'USAGE'
Usage: scripts/openbao-ui-overlay-apply.sh

Builds and applies the OpenBao KeyCape login overlay ConfigMaps and private
gateway Deployment/ClusterIP Service. Idempotent — safe on every deploy. It
does not create or delete a public Ingress.

Environment:
  OPENBAO_NAMESPACE      Kubernetes namespace. Default: openbao
  KUBECTL                  kubectl command, including --kubeconfig if needed
  OPENBAO_UI_OVERLAY_DIR   Overlay asset directory
  OPENBAO_UI_OVERLAY_K8S   Gateway manifest path
USAGE
}

if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then
  usage
  exit 0
fi

for required in overlay.css overlay.js callback.html callback.js login.css login.html login.js presets.json nginx.conf VERSION; do
  if [ ! -f "$OVERLAY_DIR/$required" ]; then
    echo "missing overlay asset: $OVERLAY_DIR/$required" >&2
    exit 1
  fi
done

if [ ! -f "$K8S_MANIFEST" ]; then
  echo "missing gateway manifest: $K8S_MANIFEST" >&2
  exit 1
fi

# shellcheck disable=SC2086
$KUBECTL create namespace "$OPENBAO_NAMESPACE" --dry-run=client -o yaml | $KUBECTL apply -f -

# shellcheck disable=SC2086
$KUBECTL create configmap openbao-ui-overlay \
  --namespace "$OPENBAO_NAMESPACE" \
  --from-file="$OVERLAY_DIR/overlay.css" \
  --from-file="$OVERLAY_DIR/overlay.js" \
  --from-file="$OVERLAY_DIR/callback.html" \
  --from-file="$OVERLAY_DIR/callback.js" \
  --from-file="$OVERLAY_DIR/login.css" \
  --from-file="$OVERLAY_DIR/login.html" \
  --from-file="$OVERLAY_DIR/login.js" \
  --from-file="$OVERLAY_DIR/presets.json" \
  --from-file="$OVERLAY_DIR/VERSION" \
  --dry-run=client -o yaml | $KUBECTL apply -f -

# shellcheck disable=SC2086
$KUBECTL create configmap openbao-ui-gateway-nginx \
  --namespace "$OPENBAO_NAMESPACE" \
  --from-file=nginx.conf="$OVERLAY_DIR/nginx.conf" \
  --dry-run=client -o yaml | $KUBECTL apply -f -

# shellcheck disable=SC2086
$KUBECTL apply -f "$K8S_MANIFEST"

# shellcheck disable=SC2086
$KUBECTL rollout restart deployment/openbao-ui-gateway -n "$OPENBAO_NAMESPACE"

# shellcheck disable=SC2086
$KUBECTL rollout status deployment/openbao-ui-gateway -n "$OPENBAO_NAMESPACE" --timeout=120s

printf '[OK] OpenBao UI overlay applied from %s\n' "$OVERLAY_DIR"
