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

OPENBAO_NAMESPACE="${OPENBAO_NAMESPACE:-openbao}"
OPENBAO_RELEASE="${OPENBAO_RELEASE:-openbao}"
KUBECTL="${KUBECTL:-kubectl}"
TOKEN_FILE="${OPENBAO_TOKEN_FILE:-}"
ROLE_NAME="${OPENBAO_ESO_ROLE:-external-secrets-issue-core}"
POLICY_NAME="${OPENBAO_ESO_POLICY:-external-secrets-issue-core}"
ESO_NAMESPACE="${ESO_NAMESPACE:-external-secrets}"
ESO_SERVICE_ACCOUNT="${ESO_SERVICE_ACCOUNT:-external-secrets}"
REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
POLICY_FILE="${POLICY_FILE:-$REPO_DIR/openbao/policies/external-secrets-issue-core.hcl}"
NEXT_KV_PATH="${OPENBAO_ESO_NEXT_PATH:-platform/workloads/issue-core/issue-core/issue-core-runtime}"
NEXT_FIELDS="${OPENBAO_ESO_NEXT_FIELDS:-ISSUE_CORE_API_KEY and GITEA_BACKEND_TOKEN}"
NEXT_TARGET="${OPENBAO_ESO_NEXT_TARGET:-ExternalSecret/issue-core-runtime}"
DRY_RUN=0

usage() {
  cat <<'USAGE'
Usage: scripts/openbao-apply-external-secrets-issue-core.sh [--dry-run]

Configures OpenBao for the issue-core External Secrets Operator pilot:
  - refreshes Kubernetes auth config for in-cluster short-lived tokens
  - writes the external-secrets-issue-core read policy
  - writes the Kubernetes auth role bound to external-secrets/external-secrets

The script reads an OpenBao operator token from OPENBAO_TOKEN_FILE or an
interactive hidden prompt. It never prints or stores the token.
USAGE
}

while [ "$#" -gt 0 ]; do
  case "$1" in
    --dry-run)
      DRY_RUN=1
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "ERROR: unknown argument: $1" >&2
      usage >&2
      exit 2
      ;;
  esac
done

pod="${OPENBAO_RELEASE}-0"

read_token() {
  if [ "$DRY_RUN" -eq 1 ]; then
    printf 'dry-run-token\n'
    return
  fi
  if [ -n "$TOKEN_FILE" ]; then
    if [ ! -f "$TOKEN_FILE" ]; then
      echo "ERROR: OPENBAO_TOKEN_FILE does not exist: $TOKEN_FILE" >&2
      exit 1
    fi
    head -n 1 "$TOKEN_FILE"
    return
  fi
  local token
  read -r -s -p "OpenBao token: " token
  printf '\n' >&2
  printf '%s\n' "$token"
}

kubectl_exec() {
  # shellcheck disable=SC2086
  $KUBECTL "$@"
}

remote_bao() {
  local token="$1"
  shift
  if [ "$DRY_RUN" -eq 1 ]; then
    printf 'DRY-RUN: bao %s\n' "$*"
    return 0
  fi
  printf '%s\n' "$token" | kubectl_exec exec -i -n "$OPENBAO_NAMESPACE" "$pod" -- \
    sh -c 'read -r BAO_TOKEN; export BAO_TOKEN; exec bao "$@"' sh "$@"
}

remote_sh() {
  local token="$1"
  local script="$2"
  if [ "$DRY_RUN" -eq 1 ]; then
    printf 'DRY-RUN: remote shell: %s\n' "$script"
    return 0
  fi
  printf '%s\n%s\n' "$token" "$script" | kubectl_exec exec -i -n "$OPENBAO_NAMESPACE" "$pod" -- \
    sh -c 'read -r BAO_TOKEN; export BAO_TOKEN; sh'
}
write_policy() {
  local token="$1"
  if [ ! -f "$POLICY_FILE" ]; then
    echo "ERROR: missing policy file: $POLICY_FILE" >&2
    exit 1
  fi
  if [ "$DRY_RUN" -eq 1 ]; then
    printf 'DRY-RUN: bao policy write %s %s\n' "$POLICY_NAME" "$POLICY_FILE"
    return 0
  fi
  { printf '%s\n' "$token"; cat "$POLICY_FILE"; } | kubectl_exec exec -i -n "$OPENBAO_NAMESPACE" "$pod" -- \
    sh -c 'read -r BAO_TOKEN; export BAO_TOKEN; bao policy write "$1" -' sh "$POLICY_NAME"
}

token="$(read_token)"
if [ -z "$token" ]; then
  echo "ERROR: empty token" >&2
  exit 1
fi

remote_bao "$token" status
remote_sh "$token" 'bao write auth/kubernetes/config \
  kubernetes_host="https://${KUBERNETES_SERVICE_HOST}:${KUBERNETES_SERVICE_PORT}" \
  disable_iss_validation=true'
write_policy "$token"
remote_bao "$token" write "auth/kubernetes/role/${ROLE_NAME}" \
  "bound_service_account_names=${ESO_SERVICE_ACCOUNT}" \
  "bound_service_account_namespaces=${ESO_NAMESPACE}" \
  "policies=${POLICY_NAME}" \
  ttl=15m

remote_bao "$token" read "auth/kubernetes/role/${ROLE_NAME}"

cat <<NEXT

External Secrets OpenBao role configured.

Next steps:
  1. Sync the external-secrets and openbao-secretstore ArgoCD Applications.
  2. Provision ${NEXT_KV_PATH} with ${NEXT_FIELDS} without printing values.
  3. Confirm ${NEXT_TARGET} becomes Ready.
NEXT
