#!/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:-}"
MOUNTS="${OPENBAO_AUTH_LISTING_MOUNTS:-netkingdom keycape}"

usage() {
  cat <<'USAGE'
Usage: scripts/openbao-tune-auth-listing.sh

Sets listing_visibility=unauth on configured OIDC auth mounts so the OpenBao
browser UI can discover netkingdom without falling back to token auth.

Environment:
  OPENBAO_TOKEN_FILE            Token file with platform-admin or root token
  OPENBAO_AUTH_LISTING_MOUNTS   Space-separated mount paths. Default: netkingdom keycape
USAGE
}

read_token() {
  if [ -n "$TOKEN_FILE" ]; then
    head -n 1 "$TOKEN_FILE"
    return
  fi
  local token
  read -r -s -p "OpenBao token: " token
  printf '\n' >&2
  printf '%s\n' "$token"
}

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

pod="${OPENBAO_RELEASE}-0"
token="$(read_token)"

for mount in $MOUNTS; do
  printf '%s\n' "$token" | $KUBECTL exec -i -n "$OPENBAO_NAMESPACE" "$pod" -- \
    bao write "sys/auth/${mount}/tune" listing_visibility=unauth
  printf '[OK] auth/%s listing_visibility=unauth\n' "$mount"
done

printf '\nVerify unauthenticated UI mount listing:\n'
curl -fsS "https://bao.coulomb.social/v1/sys/internal/ui/mounts" | python3 -m json.tool