#!/usr/bin/env bash
# Mugi pre-push hook (OPT-IN): runs Swift smoke via xcodebuild when Swift files
# changed since the last push. Slow (~30-60s) so it's installed only when the
# user passes `--with-swift` to install_git_hooks.sh.
#
# If you have this installed and it's ever blocking a legitimate push, bypass
# with `git push --no-verify`.
set -e

repo_root=$(git rev-parse --show-toplevel 2>/dev/null || pwd)
cd "$repo_root"

# Compare HEAD against upstream tracking branch to find the diff being pushed.
upstream=$(git rev-parse --abbrev-ref --symbolic-full-name '@{u}' 2>/dev/null || true)
if [ -z "$upstream" ]; then
  echo "[mugi-pre-push] no upstream tracking branch; skipping Swift smoke."
  exit 0
fi

swift_changed=$(git diff "$upstream"...HEAD --name-only --diff-filter=ACM 2>/dev/null \
  | grep -E '\.(swift|pbxproj)$' || true)

if [ -z "$swift_changed" ]; then
  exit 0
fi

echo "[mugi-pre-push] Swift / pbxproj files changed -> running Swift smoke..."
echo "                (use 'git push --no-verify' if you must skip this)"

if ! xcodebuild test \
  -project MugiApp/Mugi.xcodeproj \
  -scheme Mugi \
  -only-testing:MugiTests/PreferencesPaneSmokeTests \
  -only-testing:MugiTests/BackendInfoParserTests \
  -quiet 2>&1 | tail -40; then
  echo ""
  echo "[mugi-pre-push] SWIFT SMOKE FAILED. Push blocked."
  echo "                Fix the failing test(s) or use 'git push --no-verify'."
  exit 1
fi

echo "[mugi-pre-push] Swift smoke passed."
exit 0
