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

show_bootstrap_credentials_hint() {
  credentials=/var/lib/nucleus/runtime/bootstrap-credentials.json
  if [ ! -f "$credentials" ]; then
    return
  fi
  if [ ! -s "$credentials" ]; then
    echo "First-access credential handoff is incomplete: $credentials" >&2
    echo "Do not expect a restart to regenerate it; use the matching numin Admin password reset." >&2
    return
  fi
  mode=$(stat -c '%a' "$credentials" 2>/dev/null || true)
  if [ "$mode" != "600" ]; then
    echo "Bootstrap credential file has unsafe mode $mode; protect it before use: $credentials" >&2
    return
  fi
  echo "First-access credentials: $credentials (mode 0600)"
  echo "Move them to your secret manager, verify login, and then remove that file."
}

echo "Service state"
systemctl --no-pager --full status nucleus-server.service || true
echo

if curl --connect-timeout 3 --max-time 5 -ksSf \
  https://127.0.0.1:8443/health/live >/dev/null 2>&1; then
  echo "Liveness: healthy"
else
  echo "Liveness: unavailable"
fi
if curl --connect-timeout 3 --max-time 5 -ksSf \
  https://127.0.0.1:8443/health/ready >/dev/null 2>&1; then
  echo "Readiness: ready"
  show_bootstrap_credentials_hint
  exit 0
fi

echo "Readiness: waiting or blocked"
echo
echo "Recent lifecycle diagnostics"
journalctl \
  -u nucleus-server.service \
  --no-pager \
  -n 300 |
  grep -Ei 'product release|releaseStatus|retry|failed|error|postgres|database|workspace|recovery|schema' |
  tail -100 || true
echo
show_bootstrap_credentials_hint
echo
echo "Keep the current target release selected after a schema transition."
echo "Use the matching target numin for DeploymentPlan diagnostics."
exit 1
