#!/bin/bash
# scripts/build-display-control.sh
# Compile the display_control binary for macOS.
#
# Requirements: Xcode Command Line Tools
#   xcode-select --install
#
# Run this on a Mac. Commit the resulting binary to resources/bin/
# so it is bundled into the packaged Electron app without any Homebrew dependency.

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
SRC="$SCRIPT_DIR/display_control.m"
OUT_DIR="$REPO_ROOT/resources/bin"
OUT_BIN="$OUT_DIR/display_control"

if ! command -v clang &>/dev/null; then
    echo "ERROR: clang not found."
    echo "Install Xcode Command Line Tools:  xcode-select --install"
    exit 1
fi

mkdir -p "$OUT_DIR"

TMP_X86="$OUT_DIR/display_control_x86_64"
TMP_ARM="$OUT_DIR/display_control_arm64"

echo "Building display_control (x86_64)..."
clang -arch x86_64 -framework Cocoa -framework Carbon \
    -o "$TMP_X86" "$SRC"

echo "Building display_control (arm64)..."
clang -arch arm64 -framework Cocoa -framework Carbon \
    -o "$TMP_ARM" "$SRC"

echo "Linking universal binary..."
lipo -create -output "$OUT_BIN" "$TMP_X86" "$TMP_ARM"
rm "$TMP_X86" "$TMP_ARM"

chmod +x "$OUT_BIN"

echo ""
echo "Built universal binary: $OUT_BIN"
lipo -archs "$OUT_BIN"
echo ""
echo "Test it:"
echo "  $OUT_BIN status"
echo "  $OUT_BIN extend"
echo "  $OUT_BIN mirror"
echo ""
echo "Once verified, commit resources/bin/display_control to the repo."
