#!/bin/bash
# Assembles a double-clickable .app around the SwiftPM binary — and, when
# asked, the disk image people install it from and the ZIP the updater
# fetches.
#
#   ./build.sh                 debug-free release build, ad-hoc signed: runs here
#   Halo_DEV=1 ./build.sh    the same as a dev build: yellow icon, named for
#                              the branch (Search-split-view from
#                              claude/split-view-4a6927)
#   Halo_DEV=1 SEARCH_FEATURE=name ./build.sh
#                              the same, named Search-name
#   ./build.sh release dmg     + build/Halo.dmg, build/Halo.zip and
#                                build/appcast.json, signed with Developer ID
#                                if there is one in the keychain
#   ./build.sh release ship    + both notarised, the DMG stapled
#
#   SEARCH_ARCH=x86_64 ./build.sh release ship
#                              the same for Intel Macs, into build/intel/
#
# Same shape as the one next door: SwiftPM builds the executable, and a macOS
# app bundle is just a folder with a plist and the binary in the right place.
#
# The three files keep the same names from release to release, so the site
# links to them once and the updater reads one address forever. ./publish.sh
# copies them into the site.
#
# Two builds from 1.0.5, each for one kind of Mac: Apple Silicon, in build/,
# and Intel, in build/intel/, served from the site's search/intel/ folder
# with an appcast of its own. A single universal app would have weighed
# twice as much for everyone (10.9 MB of binary instead of 5.4). The app's
# updater reads the feed for the chip it was built for (Updater.feed).
# SEARCH_ARCH picks the chip; without it, the Mac's own.
#
# "dmg" lays the disk image's window out with dmgbuild, installed into .build
# on first use (Python 3 and a network, once).
#
# What "ship" needs, once:
#   - a Developer ID Application certificate in the login keychain
#     (SEARCH_SIGN_IDENTITY names it; otherwise the first one found is used)
#   - a notarytool profile: xcrun notarytool store-credentials "search"
#     (SEARCH_NOTARY_PROFILE names it; default "search")
#   - SEARCH_DOWNLOAD_URL, the https folder the three files are served from,
#     for the appcast. Default https://example.invalid, which is
#     where Updater.feed in Updater.swift looks.
#
# NOTES.md, next to this script, is what's new: newest release first, one
# paragraph each. The first paragraph goes into the appcast, and from there
# under the version line in Settings.
set -euo pipefail

cd "$(dirname "$0")"
CONFIG="${1:-release}"
STEP="${2:-app}"
ARCH="${SEARCH_ARCH:-$(uname -m)}"
case "$ARCH" in
  arm64) OUT="build"; SUBFOLDER="" ;;
  x86_64) OUT="build/intel"; SUBFOLDER="/intel" ;;
  *) echo "SEARCH_ARCH is arm64 or x86_64, not “$ARCH”" >&2; exit 1 ;;
esac
NAME="Halo"
APP="$OUT/$NAME.app"
BUNDLE_ID="com.almanac.halo"

# Asked for with SEARCH_DEV=1, a dev build, on a yellow plate and named for
# the feature it's built from: "search-split-view" in the menu bar, the Dock
# and ⌘Tab, so it's never taken for the installed app beside it, or for the
# dev build from another worktree. Only the name people see changes. The
# bundle id stays, so it shares the real app's settings, and so does the
# folder, build/Halo.app, which fresh.sh and the tests open. Not by
# default: a plain ./build.sh is also the people here use every day
# and the release candidates. What goes in a DMG or a ZIP is never one.
case "${SEARCH_DEV:-}" in
  0|1) DEV="$SEARCH_DEV" ;;
  "") DEV=0 ;;
  *) echo "SEARCH_DEV is 0 or 1, not “$SEARCH_DEV”" >&2; exit 1 ;;
esac
[ "$STEP" != "app" ] && [ "$DEV" = 1 ] && { echo "a dev build doesn't go in a DMG" >&2; exit 1; }
SHOWN="$NAME"
if [ "$DEV" = 1 ]; then
  # The feature: SEARCH_FEATURE, or the branch's last part, without the
  # six-character hash a worktree's name ends in (claude/split-view-4a6927
  # is split-view). A hash has a digit in it; a word like "decade" doesn't.
  FEATURE="${SEARCH_FEATURE:-$(git rev-parse --abbrev-ref HEAD 2>/dev/null || true)}"
  FEATURE="${FEATURE##*/}"
  if [[ "$FEATURE" =~ ^(.+)-([0-9a-f]{6})$ ]]; then
    STEM="${BASH_REMATCH[1]}" HASH="${BASH_REMATCH[2]}"
    [[ "$HASH" =~ [0-9] ]] && FEATURE="$STEM"
  fi
  # Only what's safe in a name and in InfoPlist.strings.
  FEATURE="$(printf '%s' "$FEATURE" | tr -cd 'A-Za-z0-9._-')"
  case "$FEATURE" in
    ""|HEAD) SHOWN="$NAME Dev" ;;   # no branch to name it for
    *) SHOWN="$NAME-$FEATURE" ;;
  esac
fi

VERSION="$(tr -d '[:space:]' < VERSION 2>/dev/null || echo "1.0.0")"
# A build number that only ever goes up, so the updater can tell newer from
# older without parsing version strings.
BUILD="$(date +%Y%m%d%H%M)"
# The oldest macOS this runs on — in the plist, and in the appcast so an
# older Mac is not handed a build it can't open.
MINIMUM="14.0"

# -Osize for a release: 14% less binary (5.39 → 4.65 MB) at the same speed —
# launch 337 against 338 ms, a scroll frame 0.26 against 0.25 ms, a key typed
# 0.41 ms either way, measured interleaved on 1.0.4 (27 Sep 2026).
SWIFTFLAGS=(-c "$CONFIG" --arch "$ARCH")
[ "$CONFIG" = "release" ] && SWIFTFLAGS+=(-Xswiftc -Osize)
swift build "${SWIFTFLAGS[@]}"

BIN_DIR="$(swift build "${SWIFTFLAGS[@]}" --show-bin-path)"
BINARY="$BIN_DIR/$NAME"

# Fallback if Swift Build placed the executable under .build/release or Products/Release
# or if the Package.swift executable target is still named Halo/Search
if [ ! -f "$BINARY" ]; then
  BINARY="$(find .build -maxdepth 4 -type f -perm +111 \( -name "$NAME" -o -name "Halo" -o -name "Halo" \) ! -path "*.dSYM/*" | head -n 1)"
fi

[ -n "$BINARY" ] && [ -f "$BINARY" ] || { echo "Could not find compiled binary for $NAME" >&2; exit 1; }
[ "$(lipo -archs "$BINARY")" = "$ARCH" ] || { echo "$BINARY is not a $ARCH binary" >&2; exit 1; }

rm -rf "$APP"
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
cp "$BINARY" "$APP/Contents/MacOS/$NAME"

# Copy any SwiftPM resource bundles if present
cp -R "$(dirname "$BINARY")"/*.bundle "$APP/Contents/Resources/" 2>/dev/null || true

# The binary says which SDK it was built with, and AppKit draws the app the
# way that SDK's macOS drew it: built with the macOS 27 SDK, a Mac on 27 gets
# 27's window buttons and controls; said to be built with an older one, it
# gets that one's. Swift Build, SwiftPM's default since Xcode 27, writes the
# oldest macOS the app runs on in both places (minos 14.0, sdk 14.0 — the
# native build system wrote sdk 27.0 from the same sources), and the app came
# out in macOS 14's looks on every Mac. The SDK it really was built with is
# put back; the oldest macOS stays as it is.
SDK="$(xcrun --sdk macosx --show-sdk-version)"
vtool -set-build-version macos "$MINIMUM" "$SDK" -replace \
  -output "$APP/Contents/MacOS/$NAME.sdk" "$APP/Contents/MacOS/$NAME"
mv "$APP/Contents/MacOS/$NAME.sdk" "$APP/Contents/MacOS/$NAME"

# The AppleScript dictionary (Scripting.swift): read-only, tabs' addresses
# and titles. The plist below points to it.
SDEF_FILE=""
if [ -f "Halo.sdef" ]; then
  cp Halo.sdef "$APP/Contents/Resources/"
  SDEF_FILE="Halo.sdef"
elif [ -f "Halo.sdef" ]; then
  cp Halo.sdef "$APP/Contents/Resources/Halo.sdef"
  SDEF_FILE="Halo.sdef"
fi

# Symbols stay out of the app. The linker leaves every function's name and a
# map back to the source in the binary — 15,000 entries, more than half of
# what the app weighed (6.5 MB of binary, 2.7 without them), and nothing the
# app reads while it runs. They are kept beside the build instead, as a dSYM
# that turns the addresses in a crash report back into names (Console, or
# atos -o build/Halo.app.dSYM/Contents/Resources/DWARF/Halo).
if [ "$CONFIG" = "release" ]; then
  rm -rf "$APP.dSYM"
  dsymutil "$BINARY" -o "$APP.dSYM" 2>/dev/null || echo "no dSYM this time" >&2
  strip -x "$APP/Contents/MacOS/$NAME"
fi

# The icon, drawn fresh each time — it is thirty lines of Swift, not an asset
# to keep in step with anything.
if [ -f "Icon/icon.swift" ]; then
  ICONSET="$OUT/AppIcon.iconset"
  ICONDOC="$OUT/AppIcon.icon"
  rm -rf "$ICONSET" "$ICONDOC"
  SEARCH_DEV="$DEV" swift Icon/icon.swift "$ICONSET" "$ICONDOC" > /dev/null
  iconutil -c icns "$ICONSET" -o "$APP/Contents/Resources/AppIcon.icns"
  rm -rf "$ICONSET"

  # macOS 26's Dark, Clear and Tinted Dock styles read the icon from an asset
  # catalog compiled from the Icon Composer document; without one the Dock
  # darkens the flat image and the mark goes black on black (#337). actool
  # comes with Xcode 26 — with anything older, or only the command-line tools,
  # the app keeps the .icns alone, as before.
  if [ -d "$ICONDOC" ] && xcrun --find actool >/dev/null 2>&1; then
    xcrun actool "$ICONDOC" \
      --compile "$APP/Contents/Resources" \
      --app-icon AppIcon \
      --minimum-deployment-target "$MINIMUM" \
      --platform macosx \
      --optimization space \
      --output-partial-info-plist "$OUT/assetcatalog.plist" >/dev/null 2>&1 || true
    rm -f "$OUT/assetcatalog.plist"
  fi
  rm -rf "$ICONDOC"
fi

# Write Info.plist with a valid CFBundleIdentifier so UNUserNotificationCenter
# and macOS launch services recognize the app bundle properly.
cat > "$APP/Contents/Info.plist" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://apple.com">
<plist version="1.0">
<dict>
    <key>CFBundleDevelopmentRegion</key>
    <string>en</string>
    <key>CFBundleDisplayName</key>
    <string>$SHOWN</string>
    <key>CFBundleExecutable</key>
    <string>$NAME</string>
    <key>CFBundleIconFile</key>
    <string>AppIcon</string>
    <key>CFBundleIconName</key>
    <string>AppIcon</string>
    <key>CFBundleIdentifier</key>
    <string>$BUNDLE_ID</string>
    <key>CFBundleInfoDictionaryVersion</key>
    <string>6.0</string>
    <key>CFBundleName</key>
    <string>$SHOWN</string>
    <key>CFBundlePackageType</key>
    <string>APPL</string>
