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

password_stdin=0
if [ "${1:-}" = "--db-password-stdin" ]; then
  password_stdin=1
  shift
fi
if [ "$#" -ne 0 ]; then
  echo "Usage: sudo nucleus-server-onboard [--db-password-stdin]" >&2
  exit 2
fi
if [ "$(id -u)" -ne 0 ]; then
  echo "Run nucleus-server-onboard with sudo." >&2
  exit 1
fi

if [ "$password_stdin" -eq 1 ]; then
  umask 077
  temporary="/etc/nucleus/.db-password.new.$$"
  IFS= read -r database_password || true
  if [ -z "$database_password" ]; then
    echo "A PostgreSQL password is required on stdin." >&2
    exit 1
  fi
  if IFS= read -r _; then
    echo "The PostgreSQL password input must contain exactly one line." >&2
    exit 1
  fi
  printf '%s\n' "$database_password" > "$temporary"
  chown root:nucleus "$temporary"
  chmod 0640 "$temporary"
  mv "$temporary" /etc/nucleus/db-password
  unset database_password
fi

if [ ! -s /etc/nucleus/db-password ]; then
  echo "PostgreSQL password missing." >&2
  echo "Pipe it once with: printf '%s\\n' \"\$PASSWORD\" | sudo nucleus-server-onboard --db-password-stdin" >&2
  exit 1
fi
chown root:nucleus /etc/nucleus/db-password
chmod 0640 /etc/nucleus/db-password

if [ ! -f /etc/nucleus/nucleus.env ]; then
  echo "Configuration template /etc/nucleus/nucleus.env is missing." >&2
  exit 1
fi
if [ ! -x /usr/bin/nucleus-server ]; then
  echo "No active Nucleus release is selected." >&2
  exit 1
fi

startup_timeout_seconds="${NUCLEUS_STARTUP_TIMEOUT_SECONDS:-1800}"
case "$startup_timeout_seconds" in
  ''|*[!0-9]*)
    echo "NUCLEUS_STARTUP_TIMEOUT_SECONDS must be a whole number of seconds." >&2
    exit 1
    ;;
esac
if [ "$startup_timeout_seconds" -lt 60 ]; then
  echo "NUCLEUS_STARTUP_TIMEOUT_SECONDS must be at least 60." >&2
  exit 1
fi

systemctl daemon-reload
systemctl enable --now nucleus-server.service

echo "Nucleus onboarding is running under systemd."
echo "Follow progress: journalctl -u nucleus-server -f"

started_at=$(date +%s)
deadline=$((started_at + startup_timeout_seconds))
next_progress=30
while [ "$(date +%s)" -lt "$deadline" ]; do
  if curl --connect-timeout 3 --max-time 5 -ksSf \
    https://127.0.0.1:8443/health/ready >/dev/null 2>&1; then
    echo "Nucleus is ready."
    credentials=/var/lib/nucleus/runtime/bootstrap-credentials.json
    if [ -s "$credentials" ] && [ "$(stat -c '%a' "$credentials")" = "600" ]; then
      echo "First-access credentials: $credentials (mode 0600)"
      echo "Move them to your secret manager, verify login, and then remove that file."
    fi
    exit 0
  fi
  readiness_payload=$(curl --connect-timeout 3 --max-time 5 -ksS \
    https://127.0.0.1:8443/health/ready 2>/dev/null || true)
  case "$readiness_payload" in
    *'"releaseStatus":"blocked"'*|*'"releaseStatus":"failed"'*)
      echo "Nucleus reported a terminal product-release state before readiness." >&2
      echo "Waiting longer cannot resolve this state." >&2
      nucleus-server-doctor || true
      exit 1
      ;;
  esac
  if systemctl is-failed --quiet nucleus-server.service; then
    echo "Nucleus failed before readiness." >&2
    nucleus-server-doctor || true
    exit 1
  fi
  elapsed=$(($(date +%s) - started_at))
  if [ "$elapsed" -ge "$next_progress" ]; then
    if [ -n "$readiness_payload" ]; then
      echo "Onboarding still running after ${elapsed}s: $readiness_payload"
    else
      echo "Onboarding still running after ${elapsed}s; waiting for the local lifecycle endpoint."
    fi
    next_progress=$((elapsed + 30))
  fi
  sleep 5
done

echo "Nucleus did not become ready within ${startup_timeout_seconds}s." >&2
echo "The service remains selected for safe diagnosis and forward recovery." >&2
nucleus-server-doctor || true
exit 1
