#!/bin/bash
# typecheck - Run a fast Swift typecheck on the Lendair iOS project via remote Mac build host.
#
# Usage (from any machine with SSH access to the build host):
#   ./scripts/typecheck
#
# What it does:
#   1. SSHes to the build host (configurable via REMOTE_HOST env var)
#   2. Pulls latest code on the Mac
#   3. Runs xcodebuild build with output filtered to errors/warnings only
#   4. Exits 0 on clean typecheck, 1 on errors
#
# Configuration:
#   REMOTE_HOST    - SSH hostname (default: hermes)
#   REMOTE_REPO    - Path to repo on the Mac (default: ~/code/lendair)
#   PROJECT_PATH   - Project path relative to repo root (default: iOS/Lendair/Lendair.xcodeproj)

set -euo pipefail

REMOTE_HOST="${REMOTE_HOST:-hermes}"
REMOTE_REPO="${REMOTE_REPO:-$HOME/code/lendair}"
PROJECT_PATH="${PROJECT_PATH:-iOS/Lendair/Lendair.xcodeproj}"
SCHEME="Lendair"

echo "=== Typecheck: connecting to $REMOTE_HOST ==="

ssh "$REMOTE_HOST" bash <<REMOTE
set -euo pipefail
cd "$REMOTE_REPO"
echo "--- Pulling latest ---"
git stash --include-untracked -q 2>/dev/null || true
git pull --rebase origin master 2>&1 | tail -3 || echo "Already up to date or pull failed"
git stash pop -q 2>/dev/null || true
echo "--- Running typecheck ---"
set +e +o pipefail
BUILD_LOG=\$(mktemp)
xcodebuild \
  -project "$PROJECT_PATH" \
  -scheme "$SCHEME" \
  -configuration Debug \
  -destination "generic/platform=iOS Simulator" \
  -jobs 4 \
  CODE_SIGNING_ALLOWED=NO \
  build > "\$BUILD_LOG" 2>&1
BUILD_EXIT=\$?
set -e -o pipefail

grep -E "\.swift:[0-9]+:[0-9]+: (error|warning):|^\*\* BUILD (SUCCEEDED|FAILED)" "\$BUILD_LOG" \
  | sed "s|$REMOTE_REPO/||g" \
  || true

rm -f "\$BUILD_LOG"
if [ "\$BUILD_EXIT" = "0" ]; then
  echo "=== PASSED ==="
else
  echo "=== FAILED ==="
fi
exit \$BUILD_EXIT
REMOTE
