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

usage() {
  cat <<'EOF'
Usage:
  ./scripts/cir/run_cir_record_sequence_remote_multi_rir.sh \
    --remote-root <path> \
    [--rir <afrinic,apnic,arin,lacnic,ripe>] \
    [--ssh-target <user@host>] \
    [--out-subdir-root <path>] \
    [--delta-count <n>] \
    [--sleep-secs <n>] \
    [--full-repo] \
    [--max-depth <n>] \
    [--max-instances <n>]
EOF
}

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
SSH_TARGET="${SSH_TARGET:-root@47.77.183.68}"
REMOTE_ROOT=""
RIRS="afrinic,apnic,arin,lacnic,ripe"
OUT_SUBDIR_ROOT=""
DELTA_COUNT=2
SLEEP_SECS=30
FULL_REPO=0
MAX_DEPTH=0
MAX_INSTANCES=1
SINGLE="$ROOT_DIR/scripts/cir/run_cir_record_sequence_remote.sh"

while [[ $# -gt 0 ]]; do
  case "$1" in
    --remote-root) REMOTE_ROOT="$2"; shift 2 ;;
    --rir) RIRS="$2"; shift 2 ;;
    --ssh-target) SSH_TARGET="$2"; shift 2 ;;
    --out-subdir-root) OUT_SUBDIR_ROOT="$2"; shift 2 ;;
    --delta-count) DELTA_COUNT="$2"; shift 2 ;;
    --sleep-secs) SLEEP_SECS="$2"; shift 2 ;;
    --full-repo) FULL_REPO=1; shift 1 ;;
    --max-depth) MAX_DEPTH="$2"; shift 2 ;;
    --max-instances) MAX_INSTANCES="$2"; shift 2 ;;
    -h|--help) usage; exit 0 ;;
    *) echo "unknown argument: $1" >&2; usage; exit 2 ;;
  esac
done

[[ -n "$REMOTE_ROOT" ]] || { usage >&2; exit 2; }
if [[ -z "$OUT_SUBDIR_ROOT" ]]; then
  OUT_SUBDIR_ROOT="target/replay/cir_sequence_remote_multi_rir_$(date -u +%Y%m%dT%H%M%SZ)"
fi

IFS=',' read -r -a ITEMS <<< "$RIRS"
for rir in "${ITEMS[@]}"; do
  args=(
    "$SINGLE"
    --rir "$rir" \
    --remote-root "$REMOTE_ROOT" \
    --ssh-target "$SSH_TARGET" \
    --out-subdir "$OUT_SUBDIR_ROOT/$rir" \
    --delta-count "$DELTA_COUNT" \
    --sleep-secs "$SLEEP_SECS" \
  )
  if [[ "$FULL_REPO" -eq 1 ]]; then
    args+=(--full-repo)
  else
    args+=(--max-depth "$MAX_DEPTH" --max-instances "$MAX_INSTANCES")
  fi
  "${args[@]}"
done

echo "$OUT_SUBDIR_ROOT"
