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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CONFIG_FILE="${INTER_RP_CONFIG:-./inter-rp.env}"
if [[ -f "$CONFIG_FILE" ]]; then
  # shellcheck disable=SC1090
  source "$CONFIG_FILE"
fi

INTER_RP_ROOT="${INTER_RP_ROOT:-/root/inter-rp-runners}"
MAX_RUNS="${MAX_RUNS:--1}"
RUN_INTERVAL_SECS="${RUN_INTERVAL_SECS:-0}"
RETAIN_RUNS="${RETAIN_RUNS:-20}"
RSS_SAMPLE_MS="${RSS_SAMPLE_MS:-500}"
ROUTINATOR_RUN_COMMAND="${ROUTINATOR_RUN_COMMAND:-}"
RPKI_CLIENT_RUN_COMMAND="${RPKI_CLIENT_RUN_COMMAND:-}"

if [[ -z "$ROUTINATOR_RUN_COMMAND" || -z "$RPKI_CLIENT_RUN_COMMAND" ]]; then
  cat >&2 <<'MSG'
ROUTINATOR_RUN_COMMAND and RPKI_CLIENT_RUN_COMMAND are required.
Each command runs with RUN_DIR, RP_ROOT, RUN_SEQ, RUN_ID and RP_NAME exported.
MSG
  exit 2
fi

mkdir -p "$INTER_RP_ROOT"

run_loop() {
  local rp_name="$1"
  local run_command="$2"
  local rp_root="$INTER_RP_ROOT/$rp_name"
  local completed="0"
  mkdir -p "$rp_root"
  while true; do
    if [[ "$MAX_RUNS" =~ ^[0-9]+$ ]] && (( completed >= MAX_RUNS )); then
      break
    fi
    "$SCRIPT_DIR/run_single_rp_with_rss.sh" \
      --rp "$rp_name" \
      --root "$rp_root" \
      --command "$run_command" \
      --retain-runs "$RETAIN_RUNS" \
      --sample-ms "$RSS_SAMPLE_MS" || true
    completed=$((completed + 1))
    if (( RUN_INTERVAL_SECS > 0 )); then
      sleep "$RUN_INTERVAL_SECS"
    fi
  done
}

run_loop routinator "$ROUTINATOR_RUN_COMMAND" >"$INTER_RP_ROOT/routinator.loop.log" 2>&1 &
ROUTINATOR_LOOP_PID=$!
run_loop rpki-client "$RPKI_CLIENT_RUN_COMMAND" >"$INTER_RP_ROOT/rpki-client.loop.log" 2>&1 &
RPKI_CLIENT_LOOP_PID=$!

cat >"$INTER_RP_ROOT/runner-pids.env" <<PIDS
ROUTINATOR_LOOP_PID=$ROUTINATOR_LOOP_PID
RPKI_CLIENT_LOOP_PID=$RPKI_CLIENT_LOOP_PID
PIDS

wait "$ROUTINATOR_LOOP_PID" "$RPKI_CLIENT_LOOP_PID"
