#!/bin/bash
# Build Lid Creak.app from a single Swift file. No Xcode project, no dependencies.
set -euo pipefail

cd "$(dirname "$0")"
APP="Lid Creak.app"
BIN="$APP/Contents/MacOS/LidCreak"

echo "==> clean"
rm -rf "$APP" LidCreak.iconset
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"

echo "==> icon"
arch -arm64 swiftc -O -swift-version 5 mkicon.swift -o /tmp/lidcreak-mkicon -framework AppKit
/tmp/lidcreak-mkicon LidCreak.iconset | sed 's/^/    /'
iconutil -c icns LidCreak.iconset -o "$APP/Contents/Resources/LidCreak.icns"
ls -lh "$APP/Contents/Resources/LidCreak.icns" | awk '{print "    icns: "$5}'

echo "==> compile (Swift $(swiftc --version | awk '{print $4}'))"
arch -arm64 swiftc -O -swift-version 5 \
  -target arm64-apple-macos13.0 \
  LidCreak.swift \
  -o "$BIN" \
  -framework AppKit -framework AVFoundation -framework IOKit -framework QuartzCore

echo "==> bundle"
cp Info.plist "$APP/Contents/Info.plist"
printf 'APPL????' > "$APP/Contents/PkgInfo"

echo "==> sign (ad-hoc)"
codesign --force --deep --sign - "$APP" 2>&1 | sed 's/^/    /'
codesign --verify --deep --strict "$APP" && echo "    signature valid"

echo "==> smoke tests"
"$BIN" --trigger-test | sed 's/^/    /'

echo "==> built: $(pwd)/$APP"
ls -lh "$BIN" | awk '{print "    binary: "$5}'
