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

CONFIG_FILE="${INTER_RP_METRICS_CONFIG:-./inter-rp-metrics.env}"
if [[ -f "$CONFIG_FILE" ]]; then
  # shellcheck disable=SC1090
  source "$CONFIG_FILE"
fi

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
INTER_RP_METRICS_EXPORTER="${INTER_RP_METRICS_EXPORTER:-ours-routinator}"
RPKI_INTER_RP_METRICS_BIN="${RPKI_INTER_RP_METRICS_BIN:-./bin/rpki_inter_rp_metrics}"
OURS_ROUTINATOR_EXPORTER="${OURS_ROUTINATOR_EXPORTER:-$SCRIPT_DIR/inter_rp_ours_routinator_exporter.py}"
OURS_RUN_ROOT="${OURS_RUN_ROOT:?OURS_RUN_ROOT is required}"
PEER_ROOT="${PEER_ROOT:-/root/inter-rp-aggregator/synced-from-200}"
LISTEN="${INTER_RP_METRICS_LISTEN:-0.0.0.0:9557}"
POLL_SECS="${INTER_RP_METRICS_POLL_SECS:-30}"
SCAN_TTL_SECONDS="${INTER_RP_SCAN_TTL_SECONDS:-20}"
INSTANCE="${INTER_RP_METRICS_INSTANCE:-remote231-inter-rp}"
LOG_DIR="${INTER_RP_METRICS_LOG_DIR:-./logs}"

mkdir -p "$LOG_DIR"
case "$INTER_RP_METRICS_EXPORTER" in
  ours-routinator)
    exec env \
      OURS_RUN_ROOT="$OURS_RUN_ROOT" \
      PEER_ROOT="$PEER_ROOT" \
      INTER_RP_INSTANCE="$INSTANCE" \
      INTER_RP_LISTEN="$LISTEN" \
      INTER_RP_SCAN_TTL_SECONDS="$SCAN_TTL_SECONDS" \
      "$OURS_ROUTINATOR_EXPORTER" \
      >>"$LOG_DIR/inter-rp-metrics.log" 2>&1
    ;;
  rust-generic)
    exec "$RPKI_INTER_RP_METRICS_BIN" \
      --ours-run-root "$OURS_RUN_ROOT" \
      --peer-root "$PEER_ROOT" \
      --listen "$LISTEN" \
      --poll-secs "$POLL_SECS" \
      --instance "$INSTANCE" \
      >>"$LOG_DIR/inter-rp-metrics.log" 2>&1
    ;;
  *)
    echo "unknown INTER_RP_METRICS_EXPORTER: $INTER_RP_METRICS_EXPORTER" >&2
    exit 2
    ;;
esac
