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

RELEASE="${RELEASE:-cuteos}"
NAMESPACE="${NAMESPACE:-cuteos}"
CHART_NAME="${CHART_NAME:-cuteos}"
if [[ -z "${FULLNAME:-}" ]]; then
  if [[ "${RELEASE}" == *"${CHART_NAME}"* ]]; then
    FULLNAME="${RELEASE}"
  else
    FULLNAME="${RELEASE}-${CHART_NAME}"
  fi
fi
BOOTSTRAP_IMAGE="${BOOTSTRAP_IMAGE:-registry.cuteos.io/cuteos/cuteos-bootstrap:latest}"
BOOTSTRAP_IMAGE_PULL_POLICY="${BOOTSTRAP_IMAGE_PULL_POLICY:-IfNotPresent}"
BOOTSTRAP_SERVICE_ACCOUNT="${BOOTSTRAP_SERVICE_ACCOUNT:-$FULLNAME}"
OPENBAO_PVC="${OPENBAO_PVC:-${FULLNAME}-openbao-data}"
NATS_SECRET_NAME="${NATS_SECRET_NAME:-${FULLNAME}-nats-auth}"
POSTGRES_SECRET_NAME="${POSTGRES_SECRET_NAME:-${FULLNAME}-postgres-auth}"
OPENBAO_DATA_MOUNT="${OPENBAO_DATA_MOUNT:-/data/openbao}"
JOB_NAME="${RELEASE}-bootstrap-$(date +%s)"
BOOTSTRAP_TIMEOUT_SECONDS="${BOOTSTRAP_TIMEOUT_SECONDS:-240}"
BOOTSTRAP_RETAIN_ARTIFACTS="${BOOTSTRAP_RETAIN_ARTIFACTS:-false}"

DB_USER="${DB_USER:-cuteos}"
DB_PASSWORD="${DB_PASSWORD:-}"
DB_NAME="${DB_NAME:-cuteos}"
DB_SSLMODE="${DB_SSLMODE:-disable}"

if [[ -z "${DB_PASSWORD}" ]]; then
  DB_PASSWORD="$(
    kubectl -n "${NAMESPACE}" get secret "${POSTGRES_SECRET_NAME}" -o jsonpath='{.data.POSTGRES_PASSWORD}' 2>/dev/null \
      | base64 --decode 2>/dev/null || true
  )"
fi
DB_PASSWORD="${DB_PASSWORD:-cuteos-dev-password}"

EVENT_FABRIC_URL="${EVENT_FABRIC_URL:-nats://${FULLNAME}-nats:4222}"
POLICY_GUARD_URL="${POLICY_GUARD_URL:-http://${FULLNAME}-opa:8181}"
SECRET_CORE_ADDR="${SECRET_CORE_ADDR:-http://${FULLNAME}-openbao:8200}"
STATE_LEDGER_DSN="${STATE_LEDGER_DSN:-postgres://${DB_USER}:${DB_PASSWORD}@${FULLNAME}-postgres:5432/${DB_NAME}?sslmode=${DB_SSLMODE}}"
BOOTSTRAP_ENSURE_EVENT_FABRIC="${BOOTSTRAP_ENSURE_EVENT_FABRIC:-true}"
EXECUTION_QUEUE_BOOTSTRAP_ENABLED="${EXECUTION_QUEUE_BOOTSTRAP_ENABLED:-true}"
EXECUTION_QUEUE_STREAM="${EXECUTION_QUEUE_STREAM:-CUTEOS_EXECUTION}"
EXECUTION_QUEUE_CONSUMER="${EXECUTION_QUEUE_CONSUMER:-execution-runner}"
EXECUTION_QUEUE_SUBJECT="${EXECUTION_QUEUE_SUBJECT:-cuteos.execution.run.requested}"
EXECUTION_QUEUE_DEADLETTER_SUBJECT="${EXECUTION_QUEUE_DEADLETTER_SUBJECT:-cuteos.execution.run.deadletter}"
EXECUTION_QUEUE_RUNS_BUCKET="${EXECUTION_QUEUE_RUNS_BUCKET:-CUTEOS_EXECUTION_RUNS}"

ADMIN_USERNAME="${ADMIN_USERNAME:-admin}"
if [[ -z "${ADMIN_PASSWORD:-}" ]]; then
  echo "error: ADMIN_PASSWORD is required for bootstrap-k8s" >&2
  echo "example: ADMIN_PASSWORD='<set-a-strong-admin-password>' make bootstrap-k8s" >&2
  exit 1
fi
ADMIN_FORCE_PASSWORD_CHANGE="${ADMIN_FORCE_PASSWORD_CHANGE:-true}"
ADMIN_DISPLAY_NAME="${ADMIN_DISPLAY_NAME:-Platform Admin}"
SEED_ROLE_USERS="${SEED_ROLE_USERS:-true}"
ROLE_USERS_FORCE_PASSWORD_CHANGE="${ROLE_USERS_FORCE_PASSWORD_CHANGE:-false}"

CONTROL_PLANE_ROLE="${CONTROL_PLANE_ROLE:-cuteos-control-plane}"
CONTROL_PLANE_POLICY="${CONTROL_PLANE_POLICY:-cuteos-control-plane}"
CONTROL_PLANE_SA="${CONTROL_PLANE_SA:-cuteos-control-plane}"
EXECUTION_RUNNER_ROLE="${EXECUTION_RUNNER_ROLE:-cuteos-execution-runner}"
EXECUTION_RUNNER_SA="${EXECUTION_RUNNER_SA:-cuteos-execution-runner}"
SECRET_MOUNT_PATH="${SECRET_MOUNT_PATH:-secret}"
CONTROL_PLANE_SECRET_PREFIX="${CONTROL_PLANE_SECRET_PREFIX:-cuteos}"
CLUSTER_ID="${CLUSTER_ID:-cluster-1}"
EVENT_TRUST_AUTO_BOOTSTRAP="${EVENT_TRUST_AUTO_BOOTSTRAP:-true}"
EVENT_SIGNER_ENABLED="${EVENT_SIGNER_ENABLED:-true}"
EVENT_TRUST_BOOTSTRAP_SECRET_FILE="${EVENT_TRUST_BOOTSTRAP_SECRET_FILE:-/data/uploads/trust/event-signing-hs256.key}"

EVENT_FABRIC_TOKEN="${EVENT_FABRIC_TOKEN:-${CUTEOS_EVENT_FABRIC_TOKEN:-${NATS_TOKEN:-${SHARED_TOKEN:-}}}}"
if [[ -z "${EVENT_FABRIC_TOKEN}" ]]; then
  EVENT_FABRIC_TOKEN="$(
    kubectl -n "${NAMESPACE}" get secret "${NATS_SECRET_NAME}" -o jsonpath='{.data.NATS_AUTH_TOKEN}' 2>/dev/null \
      | base64 --decode 2>/dev/null || true
  )"
fi

resolve_bootstrap_environment() {
  local explicit_environment="${BOOTSTRAP_ENV:-${CUTEOS_ENV:-}}"
  local deployment_name="${FULLNAME}-control-plane"
  local resolved_environment=""

  if [[ -n "${explicit_environment}" ]]; then
    printf '%s\n' "${explicit_environment}"
    return 0
  fi

  resolved_environment="$(
    kubectl -n "${NAMESPACE}" get deployment "${deployment_name}" \
      -o jsonpath='{range .spec.template.spec.containers[*].env[*]}{.name}={.value}{"\n"}{end}' 2>/dev/null \
      | awk -F= '$1 == "CUTEOS_ENV" { print $2; exit }'
  )"
  if [[ -n "${resolved_environment}" ]]; then
    printf '%s\n' "${resolved_environment}"
    return 0
  fi

  printf 'prod\n'
}

BOOTSTRAP_ENVIRONMENT="$(resolve_bootstrap_environment)"

echo "Submitting bootstrap job ${JOB_NAME} in namespace ${NAMESPACE}"
echo "Bootstrap environment: ${BOOTSTRAP_ENVIRONMENT}"

OPENBAO_VOLUME_SPEC=""
OPENBAO_SHARED_ARTIFACTS="false"
if kubectl -n "${NAMESPACE}" get pvc "${OPENBAO_PVC}" >/dev/null 2>&1; then
  OPENBAO_SHARED_ARTIFACTS="true"
  OPENBAO_VOLUME_SPEC="$(cat <<EOF
      - name: openbao-data
        persistentVolumeClaim:
          claimName: ${OPENBAO_PVC}
EOF
)"
else
  echo "info: OpenBao PVC not found (${OPENBAO_PVC}); using ephemeral bootstrap artifacts" >&2
  OPENBAO_VOLUME_SPEC="$(cat <<EOF
      - name: openbao-data
        emptyDir: {}
EOF
)"
fi

cat <<EOF | kubectl apply -f -
apiVersion: batch/v1
kind: Job
metadata:
  name: ${JOB_NAME}
  namespace: ${NAMESPACE}
spec:
  backoffLimit: 0
  ttlSecondsAfterFinished: 300
  template:
    spec:
      restartPolicy: Never
      serviceAccountName: ${BOOTSTRAP_SERVICE_ACCOUNT}
      containers:
      - name: bootstrap
        image: ${BOOTSTRAP_IMAGE}
        imagePullPolicy: ${BOOTSTRAP_IMAGE_PULL_POLICY}
        volumeMounts:
        - name: openbao-data
          mountPath: ${OPENBAO_DATA_MOUNT}
        env:
        - name: CUTEOS_ENV
          value: "${BOOTSTRAP_ENVIRONMENT}"
        - name: CUTEOS_STATE_LEDGER_DSN
          value: "${STATE_LEDGER_DSN}"
        - name: CUTEOS_EVENT_FABRIC_URL
          value: "${EVENT_FABRIC_URL}"
        - name: CUTEOS_EVENT_FABRIC_TOKEN
          value: "${EVENT_FABRIC_TOKEN}"
        - name: CUTEOS_BOOTSTRAP_ENSURE_EVENT_FABRIC
          value: "${BOOTSTRAP_ENSURE_EVENT_FABRIC}"
        - name: CUTEOS_EXECUTION_QUEUE_BOOTSTRAP_ENABLED
          value: "${EXECUTION_QUEUE_BOOTSTRAP_ENABLED}"
        - name: CUTEOS_EXECUTION_QUEUE_STREAM
          value: "${EXECUTION_QUEUE_STREAM}"
        - name: CUTEOS_EXECUTION_QUEUE_CONSUMER
          value: "${EXECUTION_QUEUE_CONSUMER}"
        - name: CUTEOS_EXECUTION_QUEUE_SUBJECT
          value: "${EXECUTION_QUEUE_SUBJECT}"
        - name: CUTEOS_EXECUTION_QUEUE_DEADLETTER_SUBJECT
          value: "${EXECUTION_QUEUE_DEADLETTER_SUBJECT}"
        - name: CUTEOS_EXECUTION_QUEUE_RUNS_BUCKET
          value: "${EXECUTION_QUEUE_RUNS_BUCKET}"
        - name: CUTEOS_NATS_TOKEN
          value: "${EVENT_FABRIC_TOKEN}"
        - name: CUTEOS_POLICY_GUARD_URL
          value: "${POLICY_GUARD_URL}"
        - name: CUTEOS_SECRET_CORE_ADDR
          value: "${SECRET_CORE_ADDR}"
        - name: CUTEOS_SECRET_CORE_TOKEN_FILE
          value: "${OPENBAO_DATA_MOUNT}/bootstrap/root.token"
        - name: CUTEOS_SECRET_CORE_TOKEN_OUTPUT
          value: "${OPENBAO_DATA_MOUNT}/bootstrap/root.token"
        - name: CUTEOS_SECRET_CORE_UNSEAL_KEY_FILE
          value: "${OPENBAO_DATA_MOUNT}/bootstrap/unseal.key"
        - name: CUTEOS_SECRET_CORE_UNSEAL_KEY_OUTPUT
          value: "${OPENBAO_DATA_MOUNT}/bootstrap/unseal.key"
        - name: CUTEOS_SECRET_CORE_INIT_IF_NEEDED
          value: "true"
        - name: CUTEOS_SECRET_CORE_ENABLE_K8S_AUTH
          value: "true"
        - name: CUTEOS_SECRET_CORE_K8S_NAMESPACE
          value: "${NAMESPACE}"
        - name: CUTEOS_SECRET_CORE_K8S_ROLE_CONTROL_PLANE
          value: "${CONTROL_PLANE_ROLE}"
        - name: CUTEOS_SECRET_CORE_K8S_SA_CONTROL_PLANE
          value: "${CONTROL_PLANE_SA}"
        - name: CUTEOS_SECRET_CORE_K8S_ROLE_EXECUTION_RUNNER
          value: "${EXECUTION_RUNNER_ROLE}"
        - name: CUTEOS_SECRET_CORE_K8S_SA_EXECUTION_RUNNER
          value: "${EXECUTION_RUNNER_SA}"
        - name: CUTEOS_BOOTSTRAP_ADMIN_USERNAME
          value: "${ADMIN_USERNAME}"
        - name: CUTEOS_BOOTSTRAP_ADMIN_PASSWORD
          value: "${ADMIN_PASSWORD}"
        - name: CUTEOS_BOOTSTRAP_ADMIN_DISPLAY_NAME
          value: "${ADMIN_DISPLAY_NAME}"
        - name: CUTEOS_BOOTSTRAP_FORCE_PASSWORD_CHANGE
          value: "${ADMIN_FORCE_PASSWORD_CHANGE}"
        - name: CUTEOS_BOOTSTRAP_SEED_ROLE_USERS
          value: "${SEED_ROLE_USERS}"
        - name: CUTEOS_BOOTSTRAP_ROLE_USERS_FORCE_PASSWORD_CHANGE
          value: "${ROLE_USERS_FORCE_PASSWORD_CHANGE}"
      volumes:
${OPENBAO_VOLUME_SPEC}
EOF

deadline=$(( $(date +%s) + BOOTSTRAP_TIMEOUT_SECONDS ))
while true; do
  succeeded="$(kubectl -n "${NAMESPACE}" get job "${JOB_NAME}" -o jsonpath='{.status.succeeded}' 2>/dev/null || echo "")"
  failed="$(kubectl -n "${NAMESPACE}" get job "${JOB_NAME}" -o jsonpath='{.status.failed}' 2>/dev/null || echo "")"
  if [[ "${succeeded:-0}" != "0" ]]; then
    kubectl -n "${NAMESPACE}" logs "job/${JOB_NAME}"
    echo "Bootstrap complete: ${JOB_NAME}"
    break
  fi
  if [[ "${failed:-0}" != "0" ]]; then
    kubectl -n "${NAMESPACE}" logs "job/${JOB_NAME}" || true
    echo "error: bootstrap job failed: ${JOB_NAME}" >&2
    exit 1
  fi
  if (( $(date +%s) >= deadline )); then
    kubectl -n "${NAMESPACE}" logs "job/${JOB_NAME}" || true
    echo "error: bootstrap job timed out after ${BOOTSTRAP_TIMEOUT_SECONDS}s: ${JOB_NAME}" >&2
    exit 1
  fi
  sleep 2
done

ROOT_TOKEN=""
if [[ "${OPENBAO_SHARED_ARTIFACTS}" == "true" ]]; then
  ROOT_TOKEN="$(kubectl -n "${NAMESPACE}" exec "deploy/${FULLNAME}-openbao" -- sh -lc "cat '${OPENBAO_DATA_MOUNT}/bootstrap/root.token'" 2>/dev/null || true)"
fi

echo "Ensuring control-plane event trust/signing bootstrap settings"
kubectl -n "${NAMESPACE}" set env deployment/"${FULLNAME}"-control-plane \
  CUTEOS_EVENT_TRUST_AUTO_BOOTSTRAP="${EVENT_TRUST_AUTO_BOOTSTRAP}" \
  CUTEOS_EVENT_TRUST_BOOTSTRAP_SECRET_FILE="${EVENT_TRUST_BOOTSTRAP_SECRET_FILE}" \
  CUTEOS_EVENT_SIGNER_ENABLED="${EVENT_SIGNER_ENABLED}" \
  CUTEOS_EVENT_SIGNER_KEY_ID="${CLUSTER_ID}" >/dev/null
kubectl -n "${NAMESPACE}" rollout status deployment/"${FULLNAME}"-control-plane --timeout=240s >/dev/null
echo "Control-plane trust/signing bootstrap settings applied"

if [[ "$(echo "${BOOTSTRAP_RETAIN_ARTIFACTS}" | tr '[:upper:]' '[:lower:]')" != "true" ]]; then
  kubectl -n "${NAMESPACE}" delete job "${JOB_NAME}" --ignore-not-found >/dev/null 2>&1 || true
  echo "Bootstrap job artifacts removed: ${JOB_NAME}"
fi

if [[ -z "${ROOT_TOKEN}" ]]; then
  if [[ "${OPENBAO_SHARED_ARTIFACTS}" == "true" ]]; then
    echo "warning: could not read OpenBao root token from ${FULLNAME}-openbao; skipping post-bootstrap policy repair"
  else
    echo "warning: OpenBao bootstrap artifacts are not shared with the cluster; skipping post-bootstrap policy repair"
  fi
  exit 0
fi

PF_PORT=18200
kubectl -n "${NAMESPACE}" port-forward "svc/${FULLNAME}-openbao" "${PF_PORT}:8200" >/tmp/cuteos-bootstrap-pf.log 2>&1 &
PF_PID=$!
trap 'kill ${PF_PID} >/dev/null 2>&1 || true' EXIT
sleep 2

POLICY_TEXT=$(cat <<EOF
path "${SECRET_MOUNT_PATH}/data/${CONTROL_PLANE_SECRET_PREFIX}/*" {
  capabilities = ["read"]
}

path "${SECRET_MOUNT_PATH}/metadata/${CONTROL_PLANE_SECRET_PREFIX}/*" {
  capabilities = ["read", "list"]
}

path "${SECRET_MOUNT_PATH}/data/${CONTROL_PLANE_SECRET_PREFIX}/domains/+/secretrefs/+" {
  capabilities = ["create", "update", "read", "delete"]
}

path "${SECRET_MOUNT_PATH}/metadata/${CONTROL_PLANE_SECRET_PREFIX}/domains/+/secretrefs/+" {
  capabilities = ["read", "list"]
}
EOF
)

POLICY_PAYLOAD="$(jq -Rn --arg p "${POLICY_TEXT}" '{policy:$p}')"
curl -fsS -X PUT \
  -H "X-Vault-Token: ${ROOT_TOKEN}" \
  -H "Content-Type: application/json" \
  -d "${POLICY_PAYLOAD}" \
  "http://127.0.0.1:${PF_PORT}/v1/sys/policies/acl/${CONTROL_PLANE_POLICY}" >/dev/null

echo "Post-bootstrap OpenBao policy repair applied for ${CONTROL_PLANE_POLICY}"

if [[ "${OPENBAO_SHARED_ARTIFACTS}" == "true" ]]; then
  if LOCAL_BOOTSTRAP_DIR="" RELEASE="${RELEASE}" NAMESPACE="${NAMESPACE}" CHART_NAME="${CHART_NAME}" FULLNAME="${FULLNAME}" \
    "${SCRIPT_DIR}/sync-openbao-bootstrap-k8s.sh" >/dev/null 2>&1; then
    echo "OpenBao bootstrap artifacts synced locally"
  else
    echo "warning: failed to sync OpenBao bootstrap artifacts locally" >&2
  fi
fi
