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

usage() {
  cat <<'EOF'
Usage:
  run_dual_local_tree_replay.sh \
    --routinator-bin <path> --routinator-mirror-root <dir> \
    --rpki-client-bin <path> --rpki-client-mirror-root <dir> \
    --tal-dir <dir> --out-dir <dir> [--validation-time <RFC3339>]
EOF
}

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROUTINATOR_BIN=""
ROUTINATOR_MIRROR_ROOT=""
RPKI_CLIENT_BIN=""
RPKI_CLIENT_MIRROR_ROOT=""
RPKI_CLIENT_CACHE_DIR=""
TAL_DIR=""
OUT_DIR=""
VALIDATION_TIME=""

while [[ $# -gt 0 ]]; do
  case "$1" in
    --routinator-bin) ROUTINATOR_BIN="$2"; shift 2 ;;
    --routinator-mirror-root) ROUTINATOR_MIRROR_ROOT="$2"; shift 2 ;;
    --rpki-client-bin) RPKI_CLIENT_BIN="$2"; shift 2 ;;
    --rpki-client-mirror-root) RPKI_CLIENT_MIRROR_ROOT="$2"; shift 2 ;;
    --rpki-client-cache-dir) RPKI_CLIENT_CACHE_DIR="$2"; shift 2 ;;
    --tal-dir) TAL_DIR="$2"; shift 2 ;;
    --out-dir) OUT_DIR="$2"; shift 2 ;;
    --validation-time) VALIDATION_TIME="$2"; shift 2 ;;
    -h|--help) usage; exit 0 ;;
    *) echo "unknown argument: $1" >&2; usage >&2; exit 2 ;;
  esac
done

if [[ -z "$RPKI_CLIENT_MIRROR_ROOT" ]]; then
  RPKI_CLIENT_MIRROR_ROOT="$ROUTINATOR_MIRROR_ROOT"
fi
[[ -n "$ROUTINATOR_BIN" && -n "$ROUTINATOR_MIRROR_ROOT" && -n "$RPKI_CLIENT_BIN" && -n "$RPKI_CLIENT_MIRROR_ROOT" && -n "$TAL_DIR" && -n "$OUT_DIR" ]] || { usage >&2; exit 2; }

mkdir -p "$OUT_DIR"
TIME_ARGS=()
if [[ -n "$VALIDATION_TIME" ]]; then
  TIME_ARGS=(--validation-time "$VALIDATION_TIME")
fi
CACHE_ARGS=()
if [[ -n "$RPKI_CLIENT_CACHE_DIR" ]]; then
  CACHE_ARGS=(--cache-dir "$RPKI_CLIENT_CACHE_DIR")
fi

"$SCRIPT_DIR/run_routinator_from_local_tree.sh" \
  --routinator-bin "$ROUTINATOR_BIN" \
  --mirror-root "$ROUTINATOR_MIRROR_ROOT" \
  --tal-dir "$TAL_DIR" \
  --out-dir "$OUT_DIR/routinator" \
  --enable-aspa \
  "${TIME_ARGS[@]}"

"$SCRIPT_DIR/run_rpki_client_from_local_tree.sh" \
  --rpki-client-bin "$RPKI_CLIENT_BIN" \
  --mirror-root "$RPKI_CLIENT_MIRROR_ROOT" \
  --tal-dir "$TAL_DIR" \
  --out-dir "$OUT_DIR/rpki-client" \
  "${CACHE_ARGS[@]}" \
  "${TIME_ARGS[@]}"

python3 "$SCRIPT_DIR/compare_normalized_sets.py" \
  --left "$OUT_DIR/routinator" \
  --right "$OUT_DIR/rpki-client" \
  --left-name routinator \
  --right-name rpki-client \
  --out "$OUT_DIR/compare-summary.json"
echo "done: $OUT_DIR"
