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

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

install -d -o nobody -g nogroup "$RP_ROOT/cache" "$RUN_DIR/output"
chown nobody:nogroup "$RUN_DIR"

timeout 1800 /root/inter-rp-runners/bin/rpki-client-official-9.8 \
  -c \
  -j \
  -t /var/lib/inter-rp-runners/fixtures/tal/afrinic.tal \
  -t /var/lib/inter-rp-runners/fixtures/tal/apnic-rfc7730-https.tal \
  -t /var/lib/inter-rp-runners/fixtures/tal/arin.tal \
  -t /var/lib/inter-rp-runners/fixtures/tal/lacnic.tal \
  -t /var/lib/inter-rp-runners/fixtures/tal/ripe-ncc.tal \
  -d "$RP_ROOT/cache" \
  "$RUN_DIR/output"

cp "$RUN_DIR/output/csv" "$RUN_DIR/vrps.csv"
cp "$RUN_DIR/output/rpki.ccr" "$RUN_DIR/result.ccr"

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

json_path, vaps_path = sys.argv[1:3]

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(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", []):
        providers = sorted({asn_text(provider) for provider in row.get("providers", [])}, key=asn_sort_key)
        writer.writerow([
            asn_text(row.get("customer_asid", row.get("customer", ""))),
            ";".join(providers),
            row.get("ta", row.get("trust_anchor", "unknown")),
        ])
PY

rm -rf "$RUN_DIR/output"
