#!/usr/bin/env bash
# Container entrypoint: run rpki_query_service (watch mode) and nginx in one
# container. nginx serves the explorer SPA and proxies /api/v1/ to the query
# service. If either process exits, the container exits and the compose
# restart policy brings it back.
set -euo pipefail

RUNS_DIR="${RUNS_DIR:-/soak/runs}"
REPO_BYTES_DB="${REPO_BYTES_DB:-/soak/db/repo-bytes.db}"
QUERY_DB="${QUERY_DB:-/data/query-db}"
RETAIN_RUNS="${RETAIN_RUNS:-10}"
WATCH_INTERVAL_SECS="${WATCH_INTERVAL_SECS:-10}"
QUERY_LISTEN="${QUERY_LISTEN:-127.0.0.1:9557}"

log() { echo "[entrypoint] $*"; }

latest_completed_seq() {
  local latest=0 dir base n
  shopt -s nullglob
  for dir in "$RUNS_DIR"/run_*/; do
    [ -f "${dir}report.json" ] || continue
    base="${dir%/}"
    n="${base##*/run_}"
    case "$n" in
      *[!0-9]* | "") continue ;;
    esac
    if [ "$n" -gt "$latest" ]; then
      latest="$n"
    fi
  done
  echo "$latest"
}

mkdir -p "$(dirname "$QUERY_DB")"

ARGS=(
  --query-db "$QUERY_DB"
  --listen "$QUERY_LISTEN"
  --watch-run-root "$RUNS_DIR"
  --watch-interval-secs "$WATCH_INTERVAL_SECS"
  --retain-indexed-runs "$RETAIN_RUNS"
)

if [ -e "$REPO_BYTES_DB" ]; then
  ARGS+=(--repo-bytes-db "$REPO_BYTES_DB")
else
  log "WARNING: repo-bytes db not found at $REPO_BYTES_DB; parsed/raw/export features will be unavailable"
fi

# Decide the watcher start point:
# - explicit WATCH_MIN_RUN_SEQ always wins;
# - on first boot (query-db does not exist yet) backfill the latest
#   RETAIN_RUNS completed runs;
# - on later boots the existing query-db drives continuation
#   (max(min_run_seq, latest_ready+1)), so no flag is needed.
if [ -n "${WATCH_MIN_RUN_SEQ:-}" ]; then
  ARGS+=(--watch-min-run-seq "$WATCH_MIN_RUN_SEQ")
  log "using explicit WATCH_MIN_RUN_SEQ=$WATCH_MIN_RUN_SEQ"
elif [ ! -e "$QUERY_DB" ]; then
  latest="$(latest_completed_seq)"
  if [ "$latest" -gt "$RETAIN_RUNS" ]; then
    min_seq=$((latest - RETAIN_RUNS + 1))
  else
    min_seq=1
  fi
  log "first boot: latest completed run seq=$latest -> --watch-min-run-seq $min_seq (backfill $RETAIN_RUNS runs)"
  ARGS+=(--watch-min-run-seq "$min_seq")
else
  log "existing query-db at $QUERY_DB; resuming from indexed state"
fi

log "starting rpki_query_service ${ARGS[*]}"
rpki_query_service "${ARGS[@]}" &
QS_PID=$!

log "starting nginx"
nginx -g 'daemon off;' &
NGINX_PID=$!

shutdown() {
  log "shutting down (qs=$QS_PID nginx=$NGINX_PID)"
  kill -TERM "$QS_PID" 2>/dev/null || true
  kill -TERM "$NGINX_PID" 2>/dev/null || true
}
trap shutdown TERM INT

wait -n "$QS_PID" "$NGINX_PID"
EXIT_CODE=$?
log "a process exited (code=$EXIT_CODE); stopping the remaining one"
shutdown
wait "$QS_PID" "$NGINX_PID" 2>/dev/null || true
exit "$EXIT_CODE"
