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

OPENBAO_NAMESPACE="${OPENBAO_NAMESPACE:-openbao}"
OPENBAO_RELEASE="${OPENBAO_RELEASE:-openbao}"
KUBECTL="${KUBECTL:-kubectl}"
MODE="${1:-basic}"

ok() { printf '[OK] %s\n' "$*"; }
warn() { printf '[WARN] %s\n' "$*"; }
err() { printf '[ERR] %s\n' "$*" >&2; }
step() { printf '\n==> %s\n' "$*"; }

usage() {
  cat <<'USAGE'
Usage: scripts/openbao-verify.sh [basic|post-unseal]

Runs non-secret OpenBao deployment checks. It never initializes, unseals, or
prints tokens.

Environment:
  OPENBAO_NAMESPACE  Kubernetes namespace. Default: openbao
  OPENBAO_RELEASE    Helm release / pod prefix. Default: openbao
  KUBECTL            kubectl command, including --kubeconfig if needed.
USAGE
}

if [ "$MODE" = "-h" ] || [ "$MODE" = "--help" ]; then
  usage
  exit 0
fi

if [ "$MODE" != "basic" ] && [ "$MODE" != "post-unseal" ]; then
  err "unknown mode: $MODE"
  usage >&2
  exit 2
fi

pod="${OPENBAO_RELEASE}-0"

check_cmd() {
  if ! command -v "${KUBECTL%% *}" >/dev/null 2>&1; then
    err "kubectl command not found: $KUBECTL"
    exit 1
  fi
}

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

check_cmd

step "OpenBao Kubernetes objects"
run get namespace "$OPENBAO_NAMESPACE" >/dev/null
ok "namespace exists: $OPENBAO_NAMESPACE"

run get pod "$pod" -n "$OPENBAO_NAMESPACE" >/dev/null
ok "pod exists: $OPENBAO_NAMESPACE/$pod"

phase="$(run get pod "$pod" -n "$OPENBAO_NAMESPACE" -o jsonpath='{.status.phase}')"
ready="$(run get pod "$pod" -n "$OPENBAO_NAMESPACE" -o jsonpath='{range .status.containerStatuses[*]}{.ready}{end}')"
printf 'Pod phase: %s\n' "$phase"
printf 'Container ready flags: %s\n' "${ready:-none}"

run get svc -n "$OPENBAO_NAMESPACE" \
  "${OPENBAO_RELEASE}" \
  "${OPENBAO_RELEASE}-active" \
  "${OPENBAO_RELEASE}-internal" \
  "${OPENBAO_RELEASE}-ui" >/dev/null
ok "expected services exist"

run get pvc -n "$OPENBAO_NAMESPACE" >/dev/null
ok "PVC query succeeded"

step "OpenBao seal/init status"
status_output=""
status_code=0
if status_output="$(run exec -n "$OPENBAO_NAMESPACE" "$pod" -- bao status 2>&1)"; then
  status_code=0
else
  status_code=$?
fi
printf '%s\n' "$status_output"

status_initialized="$(printf '%s\n' "$status_output" | awk '$1 == "Initialized" {print $2; exit}')"
status_sealed="$(printf '%s\n' "$status_output" | awk '$1 == "Sealed" {print $2; exit}')"

if [ "$status_code" -eq 0 ]; then
  ok "bao status command succeeded"
elif [ "$status_code" -eq 2 ] && [ "$status_initialized" = "false" ] && [ "$status_sealed" = "true" ]; then
  ok "OpenBao is reachable and waiting for first init/unseal ceremony"
elif [ "$status_code" -eq 2 ] && [ "$status_sealed" = "true" ]; then
  if [ "$MODE" = "basic" ]; then
    ok "OpenBao is reachable and sealed"
  else
    warn "OpenBao is still sealed; post-unseal verification is not complete"
  fi
else
  warn "bao status failed. Check pod logs and command availability."
fi

if [ "$MODE" = "basic" ]; then
  exit 0
fi

step "Post-unseal unauthenticated checks"
if run exec -n "$OPENBAO_NAMESPACE" "$pod" -- sh -c 'test -d /openbao/audit' >/dev/null 2>&1; then
  ok "audit directory exists"
else
  warn "audit directory missing or inaccessible"
fi

if run exec -n "$OPENBAO_NAMESPACE" "$pod" -- sh -c 'test -s /openbao/audit/openbao-audit.log' >/dev/null 2>&1; then
  ok "audit log file exists and is non-empty"
else
  warn "audit log file missing or empty; declarative file audit is not verified"
fi

if run exec -n "$OPENBAO_NAMESPACE" "$pod" -- sh -c 'test -d /openbao/data' >/dev/null 2>&1; then
  ok "raft data directory exists"
else
  warn "raft data directory missing or inaccessible"
fi

warn "Authenticated checks are intentionally not run here."
warn "After unseal/configuration, verify with a platform-admin token:"
warn "  bao audit list"
warn "  bao secrets list"
warn "  bao auth list"
