#!/usr/bin/env bash
# Read-only AwoooP RLS preflight runner.
#
# Default path runs inside the production API pod through the 120 control-plane
# host, so DATABASE_URL stays inside Kubernetes and is never printed locally.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PY_SCRIPT="${SCRIPT_DIR}/awooop_rls_preflight.py"

NAMESPACE="${AWOOOP_RLS_NAMESPACE:-awoooi-prod}"
DEPLOYMENT="${AWOOOP_RLS_DEPLOYMENT:-deployment/awoooi-api}"
CONTAINER="${AWOOOP_RLS_CONTAINER:-api}"
SSH_TARGET="${AWOOOP_RLS_SSH_TARGET:-wooo@192.168.0.120}"
REMOTE_KUBECTL="${AWOOOP_RLS_REMOTE_KUBECTL:-sudo kubectl}"
KUBECTL="${AWOOOP_RLS_KUBECTL:-kubectl}"
USE_SSH=1
PY_ARGS=()
SSH_OPTS=(-o BatchMode=yes -o ConnectTimeout=8)

usage() {
  cat <<'USAGE'
Usage: bash scripts/ops/awooop-rls-preflight.sh [options]

Read-only checks for AwoooP PostgreSQL RLS readiness. The script runs the Python
probe inside the API pod and exits 2 when RLS is not ready to enable.

Options:
  --exact-counts        Run exact COUNT(*) project_id backfill checks.
  --json                Print JSON output from the pod.
  --local               Use local kubectl instead of SSH to 120.
  --ssh USER@HOST       Override SSH target. Default: wooo@192.168.0.120.
  -h, --help            Show this help.

Environment:
  AWOOOP_RLS_NAMESPACE       Default: awoooi-prod
  AWOOOP_RLS_DEPLOYMENT      Default: deployment/awoooi-api
  AWOOOP_RLS_CONTAINER       Default: api
  AWOOOP_RLS_REMOTE_KUBECTL  Default: sudo kubectl
  AWOOOP_RLS_KUBECTL         Default: kubectl
USAGE
}

while [ "$#" -gt 0 ]; do
  case "$1" in
    --exact-counts)
      PY_ARGS+=(--exact-counts)
      ;;
    --json)
      PY_ARGS+=(--json)
      ;;
    --local)
      USE_SSH=0
      ;;
    --ssh)
      shift
      SSH_TARGET="${1:-}"
      if [ -z "$SSH_TARGET" ]; then
        echo "--ssh requires USER@HOST" >&2
        exit 64
      fi
      USE_SSH=1
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "Unknown argument: $1" >&2
      usage >&2
      exit 64
      ;;
  esac
  shift
done

if [ ! -f "$PY_SCRIPT" ]; then
  echo "Missing Python probe: $PY_SCRIPT" >&2
  exit 66
fi

if [ "$USE_SSH" -eq 1 ]; then
  printf -v namespace_q "%q" "$NAMESPACE"
  printf -v deployment_q "%q" "$DEPLOYMENT"
  printf -v container_q "%q" "$CONTAINER"
  remote_cmd="${REMOTE_KUBECTL} -n ${namespace_q} exec -i ${deployment_q} -c ${container_q} -- python -"
  if [ "${#PY_ARGS[@]}" -gt 0 ]; then
    for arg in "${PY_ARGS[@]}"; do
      printf -v arg_q "%q" "$arg"
      remote_cmd="${remote_cmd} ${arg_q}"
    done
  fi
  ssh "${SSH_OPTS[@]}" "$SSH_TARGET" "$remote_cmd" < "$PY_SCRIPT"
else
  if [ "${#PY_ARGS[@]}" -gt 0 ]; then
    "$KUBECTL" -n "$NAMESPACE" exec -i "$DEPLOYMENT" -c "$CONTAINER" -- python - "${PY_ARGS[@]}" < "$PY_SCRIPT"
  else
    "$KUBECTL" -n "$NAMESPACE" exec -i "$DEPLOYMENT" -c "$CONTAINER" -- python - < "$PY_SCRIPT"
  fi
fi
