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

usage() {
  cat <<'EOF'
Usage:
  ./scripts/periodic/compare_ccr_round.sh \
    --ours-ccr <path> \
    --rpki-client-ccr <path> \
    --out-dir <path> \
    [--trust-anchor <name>]
EOF
}

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
OURS_CCR=""
CLIENT_CCR=""
OUT_DIR=""
TRUST_ANCHOR="unknown"
CCR_TO_COMPARE_VIEWS_BIN="$ROOT_DIR/target/release/ccr_to_compare_views"
CCR_STATE_COMPARE_BIN="$ROOT_DIR/target/release/ccr_state_compare"

while [[ $# -gt 0 ]]; do
  case "$1" in
    --ours-ccr) OURS_CCR="$2"; shift 2 ;;
    --rpki-client-ccr) CLIENT_CCR="$2"; shift 2 ;;
    --out-dir) OUT_DIR="$2"; shift 2 ;;
    --trust-anchor) TRUST_ANCHOR="$2"; shift 2 ;;
    -h|--help) usage; exit 0 ;;
    *) echo "unknown argument: $1" >&2; usage; exit 2 ;;
  esac
done

[[ -n "$OURS_CCR" && -n "$CLIENT_CCR" && -n "$OUT_DIR" ]] || { usage >&2; exit 2; }

mkdir -p "$OUT_DIR"

if [[ ! -x "$CCR_STATE_COMPARE_BIN" || ! -x "$CCR_TO_COMPARE_VIEWS_BIN" ]]; then
  (
    cd "$ROOT_DIR"
    cargo build --release --bin ccr_state_compare --bin ccr_to_compare_views
  )
fi

OURS_VRPS="$OUT_DIR/ours-vrps.csv"
OURS_VAPS="$OUT_DIR/ours-vaps.csv"
CLIENT_VRPS="$OUT_DIR/rpki-client-vrps.csv"
CLIENT_VAPS="$OUT_DIR/rpki-client-vaps.csv"
SUMMARY_JSON="$OUT_DIR/compare-summary.json"
SUMMARY_MD="$OUT_DIR/compare-summary.md"

"$CCR_STATE_COMPARE_BIN" \
  --ours-ccr "$OURS_CCR" \
  --rpki-client-ccr "$CLIENT_CCR" \
  --out-json "$SUMMARY_JSON" \
  --out-md "$SUMMARY_MD" \
  --out-dir "$OUT_DIR" \
  --trust-anchor "$TRUST_ANCHOR" \
  --fallback-compare-views

echo "$OUT_DIR"
