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

usage() {
  cat <<'EOF'
Usage:
  ./scripts/cir/run_cir_record_sequence_ta_only_multi_rir.sh \
    [--rir <afrinic,apnic,arin,lacnic,ripe>] \
    [--delta-count <n>] \
    [--out-root <path>] \
    [--rpki-bin <path>]
EOF
}

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
HELPER_BIN="${HELPER_BIN:-$ROOT_DIR/target/release/cir_ta_only_fixture}"
MATERIALIZE_BIN="${MATERIALIZE_BIN:-$ROOT_DIR/target/release/cir_materialize}"
EXTRACT_BIN="${EXTRACT_BIN:-$ROOT_DIR/target/release/cir_extract_inputs}"
WRAPPER="$ROOT_DIR/scripts/cir/cir-rsync-wrapper"
RIRS="afrinic,apnic,arin,lacnic,ripe"
DELTA_COUNT=2
OUT_ROOT="$ROOT_DIR/target/replay/cir_sequence_multi_rir_ta_only_$(date -u +%Y%m%dT%H%M%SZ)"
RPKI_BIN="${RPKI_BIN:-$ROOT_DIR/target/release/rpki}"

while [[ $# -gt 0 ]]; do
  case "$1" in
    --rir) RIRS="$2"; shift 2 ;;
    --delta-count) DELTA_COUNT="$2"; shift 2 ;;
    --out-root) OUT_ROOT="$2"; shift 2 ;;
    --rpki-bin) RPKI_BIN="$2"; shift 2 ;;
    -h|--help) usage; exit 0 ;;
    *) echo "unknown argument: $1" >&2; usage; exit 2 ;;
  esac
done

if [[ ! -x "$HELPER_BIN" ]]; then
  (
    cd "$ROOT_DIR"
    cargo build --release --bin cir_ta_only_fixture --bin rpki --bin cir_materialize --bin cir_extract_inputs
  )
fi

case_paths() {
  case "$1" in
    afrinic) echo "tests/fixtures/tal/afrinic.tal tests/fixtures/ta/afrinic-ta.cer" ;;
    apnic) echo "tests/fixtures/tal/apnic-rfc7730-https.tal tests/fixtures/ta/apnic-ta.cer" ;;
    arin) echo "tests/fixtures/tal/arin.tal tests/fixtures/ta/arin-ta.cer" ;;
    lacnic) echo "tests/fixtures/tal/lacnic.tal tests/fixtures/ta/lacnic-ta.cer" ;;
    ripe) echo "tests/fixtures/tal/ripe-ncc.tal tests/fixtures/ta/ripe-ncc-ta.cer" ;;
    *) return 1 ;;
  esac
}

mkdir -p "$OUT_ROOT"
IFS=',' read -r -a ITEMS <<< "$RIRS"
for rir in "${ITEMS[@]}"; do
  read -r tal_rel ta_rel < <(case_paths "$rir")
  rir_root="$OUT_ROOT/$rir"
  mkdir -p "$rir_root/full"
  repo_bytes_db="$rir_root/repo-bytes.db"
  "$HELPER_BIN" \
    --tal-path "$ROOT_DIR/$tal_rel" \
    --ta-path "$ROOT_DIR/$ta_rel" \
    --tal-uri "https://example.test/$rir.tal" \
    --validation-time "2026-04-09T00:00:00Z" \
    --cir-out "$rir_root/full/input.cir" \
    --repo-bytes-db "$repo_bytes_db"
  "$EXTRACT_BIN" --cir "$rir_root/full/input.cir" --tals-dir "$rir_root/.tmp/tals" --meta-json "$rir_root/.tmp/meta.json"
  "$MATERIALIZE_BIN" --cir "$rir_root/full/input.cir" --repo-bytes-db "$repo_bytes_db" --mirror-root "$rir_root/.tmp/mirror"
  FIRST_TAL="$(python3 - <<'PY' "$rir_root/.tmp/meta.json"
import json,sys
print(json.load(open(sys.argv[1]))["talFiles"][0]["path"])
PY
)"
  export CIR_MIRROR_ROOT="$rir_root/.tmp/mirror"
  export REAL_RSYNC_BIN=/usr/bin/rsync
  export CIR_LOCAL_LINK_MODE=1
  "$RPKI_BIN" \
    --db "$rir_root/full/db" \
    --tal-path "$FIRST_TAL" \
    --disable-rrdp \
    --rsync-command "$WRAPPER" \
    --validation-time "2026-04-09T00:00:00Z" \
    --ccr-out "$rir_root/full/result.ccr" \
    --report-json "$rir_root/full/report.json" >/dev/null 2>&1
  for idx in $(seq 1 "$DELTA_COUNT"); do
    step="$(printf 'delta-%03d' "$idx")"
    mkdir -p "$rir_root/$step"
    cp "$rir_root/full/input.cir" "$rir_root/$step/input.cir"
    cp "$rir_root/full/result.ccr" "$rir_root/$step/result.ccr"
    cp "$rir_root/full/report.json" "$rir_root/$step/report.json"
  done
  python3 - <<'PY' "$rir_root" "$DELTA_COUNT"
import json, sys
from pathlib import Path
root = Path(sys.argv[1]); delta_count = int(sys.argv[2])
steps = [{"stepId":"full","kind":"full","validationTime":"2026-04-09T00:00:00Z","cirPath":"full/input.cir","ccrPath":"full/result.ccr","reportPath":"full/report.json","previousStepId":None}]
prev = "full"
for i in range(1, delta_count + 1):
    step = f"delta-{i:03d}"
    steps.append({"stepId":step,"kind":"delta","validationTime":"2026-04-09T00:00:00Z","cirPath":f"{step}/input.cir","ccrPath":f"{step}/result.ccr","reportPath":f"{step}/report.json","previousStepId":prev})
    prev = step
(root/"sequence.json").write_text(json.dumps({"version":1,"repoBytesDbPath":"repo-bytes.db","steps":steps}, indent=2), encoding="utf-8")
(root/"summary.json").write_text(json.dumps({"version":1,"stepCount":len(steps)}, indent=2), encoding="utf-8")
PY
done

python3 - <<'PY' "$OUT_ROOT" "$RIRS"
import json, sys
from pathlib import Path
root = Path(sys.argv[1]); rirs = [x for x in sys.argv[2].split(',') if x]
items=[]
for rir in rirs:
    seq=json.loads((root/rir/'sequence.json').read_text())
    items.append({"rir":rir,"stepCount":len(seq['steps'])})
(root/'summary.json').write_text(json.dumps({"version":1,"rirs":items}, indent=2), encoding='utf-8')
PY

echo "done: $OUT_ROOT"
