#!/usr/bin/env bash
# Keeps Bazel mactools builds in sync with the installed Xcode version.
#
# Only needed on runners that do mactools builds (Mac/Sparkle). Non-Mac builds
# don't run this script; their apple_cc_autoconf stays cached because none of
# its environ vars change, so they're unaffected by Xcode version changes.
#
# 1. Writes .bazelrc.xcode with mactools-scoped flags:
#    - action_env for remote cache key invalidation
#    - DEVELOPER_DIR pointing to the active Xcode
#
# 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

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

if [ -z "$XCODE_BUILD_VERSION" ]; then
    echo "Warning: Could not detect Xcode build version, skipping"
    exit 0
fi

DEVELOPER_DIR=$(xcode-select -p 2>/dev/null)

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 version changed (or first run) — expunge local cache to clear
# stale local_config_apple_cc, then write the new config
OLD_VERSION="unknown"
if [ -f "$BAZELRC_XCODE" ]; then
    OLD_VERSION=$(sed -n 's/.*XCODE_BUILD_VERSION=//p' "$BAZELRC_XCODE" | head -1)
fi
echo "Xcode build version changed: ${OLD_VERSION} -> ${XCODE_BUILD_VERSION}"
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
echo "Updated ${BAZELRC_XCODE} — next mactools build will rebuild with Xcode ${XCODE_BUILD_VERSION}"
