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

: "${RUN_DIR:?RUN_DIR is required}"
: "${RP_ROOT:?RP_ROOT is required}"

timeout 1800 /root/inter-rp-runners/bin/routinator \
  --repository-dir "$RP_ROOT/repository" \
  --no-rir-tals \
  --extra-tals-dir /var/lib/inter-rp-runners/fixtures/tal \
  --enable-aspa \
  vrps --format json --output "$RUN_DIR/routinator-output.json"

python3 - "$RUN_DIR/routinator-output.json" "$RUN_DIR/vrps.csv" "$RUN_DIR/vaps.csv" <<'PY'
import csv
import json
import sys

json_path, vrps_path, vaps_path = sys.argv[1:4]

with open(json_path, "r", encoding="utf-8") as handle:
    payload = json.load(handle)

def asn_text(value):
    if isinstance(value, int):
        return f"AS{value}"
    text = str(value)
    return text if text.startswith("AS") else f"AS{text}"

def asn_sort_key(value):
    text = asn_text(value)
    try:
        return int(text[2:])
    except ValueError:
        return text

with open(vrps_path, "w", encoding="utf-8", newline="") as handle:
    writer = csv.writer(handle)
    writer.writerow(["ASN", "IP Prefix", "Max Length", "Trust Anchor"])
    for row in payload.get("roas", []):
        writer.writerow([
            asn_text(row.get("asn", "")),
            row.get("prefix", ""),
            row.get("maxLength", row.get("max_length", "")),
            row.get("ta", row.get("trust_anchor", "")),
        ])

with open(vaps_path, "w", encoding="utf-8", newline="") as handle:
    writer = csv.writer(handle)
    writer.writerow(["Customer ASN", "Providers", "Trust Anchor"])
    for row in payload.get("aspas", payload.get("aspa", [])):
        providers = sorted({asn_text(provider) for provider in row.get("providers", [])}, key=asn_sort_key)
        writer.writerow([
            asn_text(row.get("customer", row.get("customer_asid", ""))),
            ";".join(providers),
            row.get("ta", row.get("trust_anchor", "unknown")),
        ])
PY

if [[ "${KEEP_INTER_RP_RAW_JSON:-0}" != "1" ]]; then
  rm -f "$RUN_DIR/routinator-output.json"
fi
