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

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
source "$repo_root/scripts/lib-hypertwist-sentrux.sh"
temp_root_parent="${TMPDIR:-/tmp}"
source_only_baseline_path="${HYPERTWIST_SENTRUX_SOURCE_ONLY_BASELINE_PATH:-$repo_root/.sentrux/source-only-baseline.json}"

usage() {
  cat <<EOF
Usage:
  scripts/run-hypertwist-sentrux-gate.sh [--save]

Runs sentrux gate against the HyperTwist-owned source-only mirror.

Behavior:
  --save  refreshes the persisted source-only baseline at:
          $source_only_baseline_path

Without --save, the wrapper restores that persisted baseline into the disposable
mirror before running the comparison gate.
EOF
}

save_mode=0

while [[ $# -gt 0 ]]; do
  case "$1" in
    --save)
      save_mode=1
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "Unknown argument: $1" >&2
      usage >&2
      exit 1
      ;;
  esac
done

sentrux_command="$(hypertwist_resolve_sentrux_command "$repo_root")" || {
  echo "Unable to locate sentrux. Provide HYPERTWIST_SENTRUX_BINARY, place a repo-local sentrux binary under $repo_root/tools/sentrux/bin, add sentrux to PATH, or run scripts/bootstrap-hypertwist-sentrux.sh (set HYPERTWIST_ALLOW_SIBLING_SENTRUX_BOOTSTRAP=1 only if you intentionally want legacy sibling-repo seeding on this machine)." >&2
  exit 1
}

temp_root="$(mktemp -d "${temp_root_parent%/}/hypertwist-sentrux-gate.XXXXXX")"
cleanup() {
  rm -rf "$temp_root"
}
trap cleanup EXIT

hypertwist_populate_sentrux_source_only_root "$repo_root" "$temp_root"

temp_baseline_path="$temp_root/.sentrux/baseline.json"

if [[ "$save_mode" -eq 0 ]]; then
  if [[ ! -f "$source_only_baseline_path" ]]; then
    echo "No HyperTwist source-only sentrux baseline exists yet at $source_only_baseline_path." >&2
    echo "Run scripts/run-hypertwist-sentrux-gate.sh --save once to create the baseline before requesting a comparison gate." >&2
    exit 1
  fi

  cp "$source_only_baseline_path" "$temp_baseline_path"
fi

(
  cd "$repo_root"
  if [[ "$save_mode" -eq 1 ]]; then
    "$sentrux_command" gate --save "$temp_root"
  else
    "$sentrux_command" gate "$temp_root"
  fi
)

if [[ "$save_mode" -eq 1 ]]; then
  if [[ ! -f "$temp_baseline_path" ]]; then
    echo "sentrux gate --save completed but no baseline was produced at $temp_baseline_path." >&2
    exit 1
  fi

  mkdir -p "$(dirname "$source_only_baseline_path")"
  cp "$temp_baseline_path" "$source_only_baseline_path"
  echo "Persisted HyperTwist source-only sentrux baseline to $source_only_baseline_path."
fi
