#!/usr/bin/env bash
# Wrapped Donjon intel pipeline run: update -> snapshot -> sign -> publish-prep.
# Invoked by donjon-intel-pipeline.service. Deploy to
# /opt/darkfactory/bin/run-intel-pipeline.sh (0750). Idempotent, exits non-zero
# on any failed stage so systemd OnFailure fires.
set -euo pipefail

DONJON_HOME="${DONJON_HOME:-/opt/donjon-platform}"
PY="${DONJON_PYTHON:-$DONJON_HOME/venv/bin/python3}"
DATA_DIR="$DONJON_HOME/data"
PUBLISH_CHANNEL="${DONJON_PUBLISH_CHANNEL:-releases.donjonsec.com}"
LOG_TAG="donjon-intel"

log() { echo "[$(date -u +%FT%TZ)] $*" | systemd-cat -t "$LOG_TAG" 2>/dev/null || echo "[$(date -u +%FT%TZ)] $*"; }

cd "$DONJON_HOME"

# 1) Refresh DBs + build a SIGNED snapshot in one call.
#    --sign requires DONJON_INTEL_CLASSICAL_KEY / DONJON_INTEL_PQC_KEY (from EnvironmentFile).
log "stage 1: update-intel --all --snapshot --sign"
"$PY" bin/update-intel.py --all --snapshot --sign

# 2) Verify what we just produced before publishing (fail closed).
log "stage 2: verify signed snapshot"
"$PY" bin/intel-pipeline.py verify \
    --manifest "$DATA_DIR/intel-snapshot-manifest.json" \
    --data-dir "$DATA_DIR"
VERIFY_RC=$?
if [ "$VERIFY_RC" -ne 0 ]; then
    log "ERROR: snapshot failed verification (rc=$VERIFY_RC) — NOT publishing"
    exit "$VERIFY_RC"
fi

# 3) Stage the freshest bundle for publish (publish-prep does NOT deploy).
BUNDLE="$(ls -1t "$DATA_DIR"/bundles/intel-snapshot-*.tar.gz 2>/dev/null | head -1 || true)"
if [ -n "$BUNDLE" ]; then
    log "stage 3: publish-prep $BUNDLE -> $PUBLISH_CHANNEL"
    "$PY" bin/intel-pipeline.py publish-prep --bundle "$BUNDLE" --channel "$PUBLISH_CHANNEL"
    # ACTUAL upload to OCI is gated (credentials) — uncomment once configured:
    # rclone copy "$DATA_DIR/publish/$(basename "$BUNDLE")" "oci-releases:$PUBLISH_CHANNEL/intel/"
else
    log "WARNING: no bundle found to publish"
fi

log "intel pipeline run complete"
