#!/usr/bin/env bash
# Release build of Zakuro Desktop for macOS (zc#507): universal2 zc, the app
# with the embedded widget, Developer ID signing (inside out, hardened
# runtime), notarization + stapling, a drag-to-Applications .dmg, and the
# Tauri updater archive. Run by .github/workflows/desktop-release.yml on the
# self-hosted mac-zakuro runner; runs locally the same way.
#
#   VERSION=0.0.45 ZC_ARM64=zc-darwin-arm64 ZC_X86_64=zc-darwin-x86_64 \
#     desktop/scripts/release-macos.sh            # -> desktop/dist-release/
#
# Signing (all optional; without them the build is ad-hoc signed and
# NOT notarized, and the output says so in dist-release/NOT_NOTARIZED):
#   APPLE_DEVELOPER_ID_P12          base64 of the Developer ID Application .p12
#   APPLE_DEVELOPER_ID_P12_PASSWORD its password
#   APPLE_NOTARY_KEY                base64 of the App Store Connect API key (.p8)
#   APPLE_NOTARY_KEY_ID, APPLE_NOTARY_ISSUER
#   ZAKURO_TEAM_ID                  default 398BFF43SU
set -euo pipefail

: "${VERSION:?VERSION is required (e.g. 0.0.45)}"
: "${ZC_ARM64:?ZC_ARM64: path to zc-darwin-arm64}"
: "${ZC_X86_64:?ZC_X86_64: path to zc-darwin-x86_64}"
team="${ZAKURO_TEAM_ID:-398BFF43SU}"

here="$(cd "$(dirname "$0")" && pwd)"
desk="$(cd "$here/.." && pwd)"
out="$desk/dist-release"
work="$(mktemp -d "${TMPDIR:-/tmp}/zakuro-release.XXXXXX")"
keychain="$work/release.keychain-db"
cleanup() {
  [[ -f "$keychain" ]] && security delete-keychain "$keychain" 2>/dev/null || true
  rm -rf "$work"
}
trap cleanup EXIT
rm -rf "$out" && mkdir -p "$out"

step() { printf '\n== %s\n' "$*"; }

step "zc universal2"
lipo -create -output "$work/zc" "$ZC_ARM64" "$ZC_X86_64"
chmod 755 "$work/zc"
lipo -info "$work/zc"

step "signing identity"
identity="-"
if [[ -n "${APPLE_DEVELOPER_ID_P12:-}" ]]; then
  kc_pass="$(openssl rand -hex 16)"
  security create-keychain -p "$kc_pass" "$keychain"
  security set-keychain-settings -lut 3600 "$keychain"
  security unlock-keychain -p "$kc_pass" "$keychain"
  printf '%s' "$APPLE_DEVELOPER_ID_P12" | base64 --decode > "$work/id.p12"
  security import "$work/id.p12" -k "$keychain" -P "${APPLE_DEVELOPER_ID_P12_PASSWORD:-}" \
    -T /usr/bin/codesign -T /usr/bin/security >/dev/null
  rm -f "$work/id.p12"
  security set-key-partition-list -S apple-tool:,apple: -s -k "$kc_pass" "$keychain" >/dev/null
  # Search the release keychain first, keep the user's for everything else.
  # shellcheck disable=SC2046  # one argument per existing keychain
  security list-keychains -d user -s "$keychain" $(security list-keychains -d user | tr -d '"')
  identity="$(security find-identity -v -p codesigning "$keychain" \
    | sed -n "s/.*\"\(Developer ID Application: .*($team)\)\"/\1/p" | head -1)"
  [[ -n "$identity" ]] || { echo "no 'Developer ID Application: … ($team)' identity in the .p12" >&2; exit 1; }
  echo "identity: $identity"
else
  echo "::warning::APPLE_DEVELOPER_ID_P12 is not set: ad-hoc signature, no notarization (Gatekeeper will block this build)."
fi

step "app (tauri + widget, signed inside out)"
ZC_BIN="$work/zc" ZAKURO_APP_VERSION="$VERSION" ZAKURO_SIGN_IDENTITY="$identity" \
  ZAKURO_TEAM_ID="$team" ZAKURO_BUNDLE_ID=ai.zakuro.Zakuro ZAKURO_DISPLAY_NAME=Zakuro \
  "$here/build-macos.sh"
app="$desk/build/Zakuro.app"
codesign --verify --deep --strict --verbose=2 "$app"

notarize() { # <file>
  xcrun notarytool submit "$1" --key "$work/notary.p8" --key-id "$APPLE_NOTARY_KEY_ID" \
    --issuer "$APPLE_NOTARY_ISSUER" --wait --timeout 30m --output-format json | tee "$work/notary.json"
  grep -q '"status" *: *"Accepted"' "$work/notary.json" || {
    id="$(sed -n 's/.*"id" *: *"\([^"]*\)".*/\1/p' "$work/notary.json" | head -1)"
    [[ -z "$id" ]] || xcrun notarytool log "$id" --key "$work/notary.p8" \
      --key-id "$APPLE_NOTARY_KEY_ID" --issuer "$APPLE_NOTARY_ISSUER" || true
    echo "notarization of $1 was not accepted" >&2
    exit 1
  }
}

notarized=0
if [[ "$identity" != "-" && -n "${APPLE_NOTARY_KEY:-}" ]]; then
  : "${APPLE_NOTARY_KEY_ID:?}" "${APPLE_NOTARY_ISSUER:?}"
  printf '%s' "$APPLE_NOTARY_KEY" | base64 --decode > "$work/notary.p8"
  step "notarize + staple the app"
  ditto -c -k --keepParent "$app" "$work/Zakuro.zip"
  notarize "$work/Zakuro.zip"
  xcrun stapler staple "$app"
  spctl --assess --type execute --verbose=2 "$app"
  notarized=1
elif [[ "$identity" != "-" ]]; then
  echo "::warning::APPLE_NOTARY_KEY is not set: signed but NOT notarized."
fi

step "dmg"
dmg="$out/Zakuro_${VERSION}_universal.dmg"
stage="$work/dmg"
mkdir -p "$stage"
ditto "$app" "$stage/Zakuro.app"
ln -s /Applications "$stage/Applications"
hdiutil create -volname "Zakuro" -srcfolder "$stage" -fs HFS+ -format UDZO -ov "$dmg" >/dev/null
[[ "$identity" == "-" ]] || codesign --force --timestamp --sign "$identity" "$dmg"
if [[ "$notarized" == 1 ]]; then
  step "notarize + staple the dmg"
  notarize "$dmg"
  xcrun stapler staple "$dmg"
  xcrun stapler validate "$dmg"
  spctl --assess --type open --context context:primary-signature --verbose=2 "$dmg"
fi

step "updater archive"
COPYFILE_DISABLE=1 tar -czf "$out/Zakuro_universal.app.tar.gz" -C "$(dirname "$app")" Zakuro.app

[[ "$notarized" == 1 ]] || echo "identity=$identity (not notarized)" > "$out/NOT_NOTARIZED"
(cd "$out" && shasum -a 256 Zakuro_* | tee SHA256SUMS-macos)
ls -l "$out"
