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

ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
UPSTREAM_DIR="$ROOT_DIR/../linuxcnc"
BASELINE_FILE="$ROOT_DIR/tools/upstream-baseline.txt"

if [[ ! -d "$UPSTREAM_DIR/.git" ]]; then
  echo "missing upstream git repository: $UPSTREAM_DIR" >&2
  exit 1
fi

if [[ ! -f "$BASELINE_FILE" ]]; then
  echo "missing upstream baseline file: $BASELINE_FILE" >&2
  exit 1
fi

expected="$(sed -n '1p' "$BASELINE_FILE" | tr -d '[:space:]')"
actual="$(git -C "$UPSTREAM_DIR" rev-parse HEAD)"

if [[ -z "$expected" ]]; then
  echo "empty upstream baseline file: $BASELINE_FILE" >&2
  exit 1
fi

if [[ "$actual" != "$expected" ]]; then
  echo "upstream baseline mismatch:" >&2
  echo "  expected: $expected" >&2
  echo "  actual:   $actual" >&2
  echo "Update tools/upstream-baseline.txt and docs/scope-and-baseline.md only after an intentional upstream sync." >&2
  exit 1
fi

echo "upstream baseline validation complete"
