#!/usr/bin/env bash
# Keeps Bazel macOS builds in sync with the installed Xcode version.
#
# Needed on macOS runners and developer machines because Bazel's generated
# local_config_xcode/local_config_apple_cc repositories bake in the discovered
# Xcode version. If Xcode is upgraded in place, the DEVELOPER_DIR path stays the
# same, so Bazel can otherwise keep using stale Xcode metadata.
#
# 1. Writes .bazelrc.xcode with mactools-scoped flags:
#    - action_env for Apple build remote cache key invalidation
#    - DEVELOPER_DIR pointing to the active Xcode for Apple builds
#
# 2. Runs `bazel clean --expunge` when the version actually changes, because
#    local_config_apple_cc (a cached repository rule) bakes in the old version
#    and can only be refreshed by clearing the output base.
#
# .bazelrc imports the generated file via: try-import %workspace%/.bazelrc.xcode

set -euo pipefail

DEVELOPER_DIR=""
if [ -d "/Applications/Xcode.app/Contents/Developer" ]; then
    DEVELOPER_DIR="/Applications/Xcode.app/Contents/Developer"
else
    DEVELOPER_DIR=$(xcode-select -p 2>/dev/null || true)
fi

XCODE_BUILD_VERSION=$(DEVELOPER_DIR="$DEVELOPER_DIR" xcodebuild -version 2>/dev/null | awk '/Build version/ {print $3}' || true)

if [ -z "$XCODE_BUILD_VERSION" ]; then
    echo "ERROR: Could not detect full Xcode build version."
    echo "mactools/Sparkle builds require full Xcode, not just Command Line Tools."
    echo "Install Xcode at /Applications/Xcode.app or select it with xcode-select."
    exit 1
fi

BAZELRC_XCODE=".bazelrc.xcode"
EXPECTED_LINE="common:mactools --action_env=XCODE_BUILD_VERSION=${XCODE_BUILD_VERSION}"

# Check if the file already has the right version (first line is the version marker)
if [ -f "$BAZELRC_XCODE" ]; then
    CURRENT_FIRST_LINE=$(head -1 "$BAZELRC_XCODE")
    if [ "$CURRENT_FIRST_LINE" = "$EXPECTED_LINE" ]; then
        exit 0
    fi
fi

# Xcode Bazel config changed (or first run) — expunge local cache to clear
# stale local_config_apple_cc, then write the new config
OLD_CONFIG="missing"
if [ -f "$BAZELRC_XCODE" ]; then
    OLD_CONFIG=$(head -1 "$BAZELRC_XCODE")
fi
echo "Xcode Bazel config changed: ${OLD_CONFIG} -> ${EXPECTED_LINE}"
echo "Running bazel clean --expunge to clear stale toolchain config..."
bazel clean --expunge 2>/dev/null || true

cat > "$BAZELRC_XCODE" << EOF
${EXPECTED_LINE}
common:mactools --repo_env=DEVELOPER_DIR=${DEVELOPER_DIR}
EOF

if [ -n "${GITHUB_ENV:-}" ]; then
    echo "DEVELOPER_DIR=${DEVELOPER_DIR}" >> "$GITHUB_ENV"
fi

echo "Updated ${BAZELRC_XCODE} — next macOS Bazel build will rebuild with Xcode ${XCODE_BUILD_VERSION}"
