#!/usr/bin/env bash
set -euo pipefail

usage() {
  cat <<'EOF'
Build the signed Electron application for macOS arm64 and x64.

Usage:
  ./build-macos-assets.sh <version> [--build-only]

Electron Builder produces two DMGs, two updater ZIPs, and latest-mac.yml from
one canonical application version. The default mode uploads them under
agentteam/desktop/. --build-only skips upload.

Signing/notarization are enabled by default for this release entrypoint.
When the P12 contains only a private key, also set AGENTTEAM_MACOS_CODESIGN_CERT to
the matching Developer ID Application certificate.
For an ad-hoc host smoke test use:
  AGENTTEAM_MACOS_CODESIGN=0 AGENTTEAM_MACOS_NOTARIZE=0 ./build-macos-assets.sh <version> --build-only
EOF
}

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=manual-owner-client-assets.lib.sh
source "${SCRIPT_DIR}/manual-owner-client-assets.lib.sh"

version="${1:-}"
if [[ -z "${version}" ]]; then
  usage >&2
  exit 1
fi
if [[ "${version}" == -h || "${version}" == --help ]]; then
  usage
  exit 0
fi
shift

build_only=0
while [[ $# -gt 0 ]]; do
  case "$1" in
    --build-only) build_only=1 ;;
    *) fail "unknown argument: $1" ;;
  esac
  shift
done

init_manual_owner_client_assets "${version}"
trap cleanup_macos_builder_signing_env EXIT
export AGENTTEAM_MACOS_CODESIGN="${AGENTTEAM_MACOS_CODESIGN:-1}"
export AGENTTEAM_MACOS_NOTARIZE="${AGENTTEAM_MACOS_NOTARIZE:-1}"
if [[ "${build_only}" -eq 0 ]] &&
   { ! truthy "${AGENTTEAM_MACOS_CODESIGN}" || ! truthy "${AGENTTEAM_MACOS_NOTARIZE}"; }; then
  fail "macOS unsigned or unnotarized packages are local-only; rerun with --build-only or configure Developer ID signing and notarization"
fi
build_macos_assets
if [[ "${build_only}" -eq 0 ]]; then
  ensure_ks3util_bin
  upload_macos_assets
fi
print_macos_summary
