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

usage() {
  cat <<'EOF'
Usage:
  build_local_repo_replay_package.sh --out <path> [--tar-gz]

Build a standalone local repository tree replay package for Routinator and
rpki-client. The package does not include repository data and does not include
materialize tooling.
EOF
}

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
SRC_DIR="$ROOT_DIR/scripts/local_repo_replay"
OUT=""
TAR_GZ=0

while [[ $# -gt 0 ]]; do
  case "$1" in
    --out) OUT="$2"; shift 2 ;;
    --tar-gz) TAR_GZ=1; shift ;;
    -h|--help) usage; exit 0 ;;
    *) echo "unknown argument: $1" >&2; usage >&2; exit 2 ;;
  esac
done

[[ -n "$OUT" ]] || { usage >&2; exit 2; }

if [[ "$TAR_GZ" -eq 1 ]]; then
  PACKAGE_DIR="$(mktemp -d)"
  TARGET_DIR="$PACKAGE_DIR/local-repo-replay-package"
else
  TARGET_DIR="$OUT"
  rm -rf "$TARGET_DIR"
fi

mkdir -p "$TARGET_DIR/scripts" "$TARGET_DIR/docs" "$TARGET_DIR/examples"

install -m 0755 "$SRC_DIR/run_routinator_from_local_tree.sh" "$TARGET_DIR/scripts/"
install -m 0755 "$SRC_DIR/run_rpki_client_from_local_tree.sh" "$TARGET_DIR/scripts/"
install -m 0755 "$SRC_DIR/run_dual_local_tree_replay.sh" "$TARGET_DIR/scripts/"
install -m 0755 "$SRC_DIR/prepare_tals.py" "$TARGET_DIR/scripts/"
install -m 0755 "$SRC_DIR/normalize_rp_outputs.py" "$TARGET_DIR/scripts/"
install -m 0755 "$SRC_DIR/compare_normalized_sets.py" "$TARGET_DIR/scripts/"
install -m 0755 "$SRC_DIR/summarize_replay.py" "$TARGET_DIR/scripts/"
install -m 0755 "$ROOT_DIR/scripts/cir/cir-rsync-wrapper" "$TARGET_DIR/scripts/"
install -m 0755 "$ROOT_DIR/scripts/cir/cir-local-link-sync.py" "$TARGET_DIR/scripts/"
install -m 0644 "$SRC_DIR/templates/README.md" "$TARGET_DIR/README.md"
install -m 0644 "$SRC_DIR/templates/docs/input_tree_requirements.md" "$TARGET_DIR/docs/"
install -m 0644 "$SRC_DIR/templates/docs/offline_replay_limits.md" "$TARGET_DIR/docs/"
install -m 0644 "$SRC_DIR/templates/docs/output_files.md" "$TARGET_DIR/docs/"
install -m 0755 "$SRC_DIR/templates/examples/routinator_example.sh" "$TARGET_DIR/examples/"
install -m 0755 "$SRC_DIR/templates/examples/rpki_client_example.sh" "$TARGET_DIR/examples/"
install -m 0755 "$SRC_DIR/templates/examples/dual_compare_example.sh" "$TARGET_DIR/examples/"
cat > "$TARGET_DIR/env.example" <<'EOF'
# 本地目录树 replay 示例配置。目录树由使用者提前准备，不包含在 package 中。
TAL_DIR=/data/replay/tals
MIRROR_ROOT=/data/replay/mirror
ROUTINATOR_BIN=/opt/routinator/target/release/routinator
RPKI_CLIENT_BIN=/opt/rpki-client/src/rpki-client
RPKI_CLIENT_CACHE_DIR=/data/replay/work/rpki-client-cache
VALIDATION_TIME=2026-05-23T00:00:00Z
EOF

if grep -R -E 'cir_materialize|repo-bytes\\.db|\\.cir' "$TARGET_DIR/scripts" >/dev/null; then
  echo "package contains forbidden materialize/repo-bytes implementation references" >&2
  exit 1
fi

if [[ "$TAR_GZ" -eq 1 ]]; then
  mkdir -p "$(dirname "$OUT")"
  tar -C "$PACKAGE_DIR" -czf "$OUT" local-repo-replay-package
  rm -rf "$PACKAGE_DIR"
  echo "$OUT"
else
  echo "$TARGET_DIR"
fi
