#!/usr/bin/env bash
# Post-build step (macOS): build macos/ZakuroWidget with xcodegen + xcodebuild,
# embed the .appex in the Tauri app's Contents/PlugIns, then sign the bundle
# inside out (widget, zc sidecar, app).
#
#   embed-widget.sh <path/to/Zakuro.app>
#
# Signing is a parameter so M1.2 can plug in the Developer ID (zc#505/#507):
#   ZAKURO_SIGN_IDENTITY  codesign identity, default "-" (ad-hoc, local builds)
#   ZAKURO_TEAM_ID        team for the App Group prefix, default 398BFF43SU
#   ZAKURO_WIDGET_ARCHS   default "arm64 x86_64" (universal2)
set -euo pipefail

app="${1:?usage: embed-widget.sh <path/to/Zakuro.app>}"
[[ -d "$app/Contents/MacOS" ]] || { echo "not an app bundle: $app" >&2; exit 1; }
app="$(cd "$app" && pwd)"

here="$(cd "$(dirname "$0")" && pwd)"
repo="$(cd "$here/../.." && pwd)"
identity="${ZAKURO_SIGN_IDENTITY:--}"
team="${ZAKURO_TEAM_ID:-398BFF43SU}"
archs="${ZAKURO_WIDGET_ARCHS:-arm64 x86_64}"
build="$repo/desktop/build"
derived="$build/widget-derived"
mkdir -p "$build"

command -v xcodegen >/dev/null || { echo "xcodegen not found: brew install xcodegen" >&2; exit 1; }

# 1. The widget, unsigned: this script signs it below with the identity above.
#    TeamIdentifierPrefix is what $(TeamIdentifierPrefix)ai.zakuro.shared in the
#    widget's Info.plist expands to, so the App Group matches the app's.
xcodegen generate --quiet --spec "$repo/macos/project.yml"
xcodebuild build \
  -project "$repo/macos/Zakuro.xcodeproj" -scheme Zakuro \
  -configuration Release -destination 'generic/platform=macOS' \
  -derivedDataPath "$derived" \
  ARCHS="$archs" ONLY_ACTIVE_ARCH=NO \
  CODE_SIGNING_ALLOWED=NO CODE_SIGNING_REQUIRED=NO \
  DEVELOPMENT_TEAM="$team" TeamIdentifierPrefix="$team." \
  -quiet
appex="$derived/Build/Products/Release/ZakuroWidget.appex"
[[ -d "$appex" ]] || { echo "xcodebuild produced no $appex" >&2; exit 1; }

# 2. Embed.
mkdir -p "$app/Contents/PlugIns"
rm -rf "$app/Contents/PlugIns/ZakuroWidget.appex"
cp -R "$appex" "$app/Contents/PlugIns/"

# 3. Sign inside out. Entitlements come from macos/ (one source of truth), with
#    $(TeamIdentifierPrefix) expanded.
ents="$build/entitlements"
mkdir -p "$ents"
for f in ZakuroWidget/ZakuroWidget.entitlements Zakuro/Zakuro.entitlements; do
  sed "s/\$(TeamIdentifierPrefix)/$team./g" "$repo/macos/$f" > "$ents/$(basename "$f")"
done

sign_args=(--force --options runtime --sign "$identity")
[[ "$identity" == "-" ]] || sign_args+=(--timestamp)

codesign "${sign_args[@]}" --entitlements "$ents/ZakuroWidget.entitlements" \
  "$app/Contents/PlugIns/ZakuroWidget.appex"
codesign "${sign_args[@]}" "$app/Contents/MacOS/zc"
codesign "${sign_args[@]}" --entitlements "$ents/Zakuro.entitlements" "$app"

codesign --verify --deep --strict "$app"
echo "embedded + signed ($identity): $app"
codesign -dv "$app/Contents/PlugIns/ZakuroWidget.appex" 2>&1 | grep -E '^(Identifier|Signature|TeamIdentifier)='
