#!/usr/bin/env bash
#
# build.sh — compile with SwiftPM, assemble a macOS .app bundle, codesign.
#
# Usage:  ./build.sh [debug|release]
#
# Driven by the Makefile. NO Xcode IDE, NO xcodebuild — `swift build` does
# the compile, this script does the bundling and signing. Xcode is only a
# toolchain provider (swift / codesign).
#
# Environment:
#   SIGN_IDENTITY      codesign identity. Defaults to ad-hoc ("-"), which is
#                      all you need for `make run` on your own machine.
#   PROVISION_PROFILE  optional .provisionprofile to embed (release/dist).
#   VERSION            CFBundleShortVersionString to stamp (default 0.0.0).
#
set -euo pipefail

CONFIG="${1:-debug}"
APP_NAME="FaceMaker"
BUILD_DIR="build"
APP="$BUILD_DIR/$APP_NAME.app"
SIGN_IDENTITY="${SIGN_IDENTITY:--}"
PROVISION_PROFILE="${PROVISION_PROFILE:-}"
VERSION="${VERSION:-0.0.0}"
ENTITLEMENTS="$APP_NAME/$APP_NAME.entitlements"
INFO_PLIST_SRC="Resources/Info.plist"

# Build number: monotonic-ish from the date so re-signs differ. Falls back to 1.
BUILD_NUMBER="$(date +%Y%m%d%H%M 2>/dev/null || echo 1)"

echo "→ swift build -c $CONFIG"
SWIFT="${SWIFT:-swift}"
"$SWIFT" build -c "$CONFIG" --scratch-path .build-make

BIN_PATH="$("$SWIFT" build -c "$CONFIG" --scratch-path .build-make --show-bin-path)"
EXECUTABLE="$BIN_PATH/$APP_NAME"
if [ ! -x "$EXECUTABLE" ]; then
	echo "✗ executable not found at $EXECUTABLE" >&2
	exit 1
fi

# ---------------------------------------------------------------------------
# Assemble the bundle
# ---------------------------------------------------------------------------
echo "→ assembling $APP"
rm -rf "$APP"
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"

cp "$EXECUTABLE" "$APP/Contents/MacOS/$APP_NAME"

# Info.plist — substitute version placeholders.
sed -e "s/__SHORT_VERSION__/$VERSION/g" \
    -e "s/__BUILD_VERSION__/$BUILD_NUMBER/g" \
    "$INFO_PLIST_SRC" > "$APP/Contents/Info.plist"

# PkgInfo — classic 8-byte file some macOS code paths still look for.
printf 'APPL????' > "$APP/Contents/PkgInfo"

# SwiftPM resource bundles — if any dependency ships a `*.bundle`, copy it
# into Contents/Resources so the app finds it once moved away from `.build`.
for bundle in "$BIN_PATH"/*.bundle; do
	if [ -e "$bundle" ]; then
		cp -R "$bundle" "$APP/Contents/Resources/"
		echo "  bundled $(basename "$bundle")"
	fi
done

# ONNX Runtime dylib — the binary links @rpath/libonnxruntime.1.dylib with
# an @executable_path/../Frameworks rpath.
mkdir -p "$APP/Contents/Frameworks"
cp "Vendor/onnxruntime/lib/libonnxruntime.1.30.0.dylib" \
   "$APP/Contents/Frameworks/libonnxruntime.1.dylib"
codesign --force --sign "$SIGN_IDENTITY" "$APP/Contents/Frameworks/libonnxruntime.1.dylib" 2>/dev/null \
	|| codesign --force --sign - "$APP/Contents/Frameworks/libonnxruntime.1.dylib"

# The face models are in ./models (fetched and converted by
# models/download.sh), about 2 GB. Link the bundle to that folder rather
# than copying them into every build.
if [ -d "models" ]; then
	rm -rf "$APP/Contents/Resources/Models"
	ln -s ../../../../models "$APP/Contents/Resources/Models"
	echo "  linked models"
fi

# App icon (optional — generated by `make icon`).
if [ -f "$BUILD_DIR/AppIcon.icns" ]; then
	cp "$BUILD_DIR/AppIcon.icns" "$APP/Contents/Resources/AppIcon.icns"
else
	echo "  (no $BUILD_DIR/AppIcon.icns — run 'make icon'; bundling without one)"
fi

# Embed a provisioning profile if one was supplied.
if [ -n "$PROVISION_PROFILE" ] && [ -f "$PROVISION_PROFILE" ]; then
	cp "$PROVISION_PROFILE" "$APP/Contents/embedded.provisionprofile"
	echo "  embedded provisioning profile"
fi

# ---------------------------------------------------------------------------
# Codesign — try the named identity, fall back to ad-hoc so `make run`
# always works on a fresh machine without certs.
# ---------------------------------------------------------------------------
sign_args=(--force --sign "$SIGN_IDENTITY")
if [ -f "$ENTITLEMENTS" ]; then
	sign_args+=(--entitlements "$ENTITLEMENTS")
fi

echo "→ codesign ($SIGN_IDENTITY)"
if ! codesign "${sign_args[@]}" "$APP" 2>/dev/null; then
	echo "  identity '$SIGN_IDENTITY' unavailable — falling back to ad-hoc (-)"
	codesign --force --sign - ${ENTITLEMENTS:+--entitlements "$ENTITLEMENTS"} "$APP"
fi

codesign --verify --verbose=1 "$APP"
echo "✓ built $APP"
