#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
# The app's marketing version is Heinzel's version in pyproject.toml; an explicit argument must equal it.
heinzel_version=$(sed -n 's/^version = "\(.*\)"$/\1/p' ../pyproject.toml | head -1)
version=${1:-$heinzel_version}
[[ $version =~ ^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$ ]]
if [[ "$version" != "$heinzel_version" ]]; then
    printf 'Version %s differs from pyproject.toml (%s).\n' "$version" "$heinzel_version" >&2
    exit 2
fi
https_links=${HEINZEL_HTTPS_LINKS:-NO}
case "$https_links" in
    YES|NO) ;;
    *) printf '%s\n' 'HEINZEL_HTTPS_LINKS must be YES or NO.' >&2; exit 2 ;;
esac
if [[ "$https_links" == YES ]]; then
    printf '%s\n' 'HTTPS links require a signed Mac Associated Domains capability; Mac packaging does not support it yet.' >&2
    exit 2
fi
signing=()
distribution=${HEINZEL_MAC_DISTRIBUTION:-development}
case "$distribution" in
    development|developer-id) ;;
    *) printf '%s\n' 'HEINZEL_MAC_DISTRIBUTION must be development or developer-id.' >&2; exit 2 ;;
esac
widget_refresh=${HEINZEL_MAC_WIDGET_REFRESH:-NO}
case "$widget_refresh" in
    YES|NO) ;;
    *) printf '%s\n' 'HEINZEL_MAC_WIDGET_REFRESH must be YES or NO.' >&2; exit 2 ;;
esac
cloud_sign_in=${HEINZEL_ICLOUD_SIGN_IN:-NO}
case "$cloud_sign_in" in
    YES|NO) ;;
    *) printf '%s\n' 'HEINZEL_ICLOUD_SIGN_IN must be YES or NO.' >&2; exit 2 ;;
esac
if [[ -n "${HEINZEL_MAC_SIGNING_TEAM:-}" ]]; then
    [[ "$HEINZEL_MAC_SIGNING_TEAM" =~ ^[A-Z0-9]{10}$ ]]
    signing+=("DEVELOPMENT_TEAM=$HEINZEL_MAC_SIGNING_TEAM"
        "HEINZEL_MAC_WIDGET_ENTITLEMENTS=Widgets/MacWidgetGroup.entitlements")
    if [[ "$cloud_sign_in" == NO ]]; then
        signing+=("HEINZEL_MAC_ENTITLEMENTS=App/MacWidgetApp.entitlements")
    fi
fi
if [[ "$cloud_sign_in" == YES || "$widget_refresh" == YES ]]; then
    if [[ -z "${HEINZEL_MAC_SIGNING_TEAM:-}" || -z "${HEINZEL_MAC_PROFILE:-}" || -z "${HEINZEL_MAC_WIDGET_PROFILE:-}" ]]; then
        printf '%s\n' 'iCloud sign-in requires HEINZEL_MAC_SIGNING_TEAM, HEINZEL_MAC_PROFILE and HEINZEL_MAC_WIDGET_PROFILE.' >&2
        exit 2
    fi
    if [[ "$HEINZEL_MAC_PROFILE" == "$HEINZEL_MAC_WIDGET_PROFILE" ]]; then
        printf '%s\n' 'iCloud sign-in requires separate Mac app and widget provisioning profiles.' >&2
        exit 2
    fi
    signing+=("CODE_SIGN_STYLE=Manual" "CODE_SIGN_IDENTITY=Apple Development"
        "HEINZEL_MAC_ENTITLEMENTS=App/MacCloudSignIn.entitlements"
        "HEINZEL_MAC_PROFILE=$HEINZEL_MAC_PROFILE"
        "HEINZEL_MAC_WIDGET_PROFILE=$HEINZEL_MAC_WIDGET_PROFILE")
fi
if [[ "$widget_refresh" == YES ]]; then
    signing+=("HEINZEL_MAC_ENTITLEMENTS=App/MacWidgetRefresh.entitlements"
        "HEINZEL_MAC_WIDGET_ENTITLEMENTS=Widgets/MacWidgetRefresh.entitlements")
fi
if [[ "$distribution" == developer-id ]]; then
    if [[ ! ${HEINZEL_MAC_SIGNING_TEAM:-} =~ ^[A-Z0-9]{10}$ ||
          -z ${HEINZEL_MAC_NOTARY_PROFILE:-} || "$cloud_sign_in" != NO || "$widget_refresh" != NO ||
          -n ${HEINZEL_MAC_PROFILE:-} || -n ${HEINZEL_MAC_WIDGET_PROFILE:-} ]]; then
        printf '%s\n' 'Developer ID requires a signing Team and notary profile, using only the Mac local widget group.' >&2
        exit 2
    fi
    # Use the explicit app and widget entitlements without Xcode adding debugger access.
    signing+=("CODE_SIGN_STYLE=Manual" "CODE_SIGN_IDENTITY=Developer ID Application"
        "CODE_SIGN_INJECT_BASE_ENTITLEMENTS=NO" "OTHER_CODE_SIGN_FLAGS=--timestamp")
    notary_keychain=()
    if [[ -n ${HEINZEL_MAC_NOTARY_KEYCHAIN:-} ]]; then
        notary_keychain+=(--keychain "$HEINZEL_MAC_NOTARY_KEYCHAIN")
    fi
fi
out="$PWD/.build/package"
mkdir -p "$out"
archive="$out/heinzel-desktop-swift-$version-darwin-arm64.tar.gz"
stage="$(mktemp -d "$out/.package.XXXXXXXX")"
trap 'rm -rf -- "$stage"' EXIT
candidate="$stage/${archive##*/}"
revision=$(git rev-parse HEAD)
xcodebuild -scheme Heinzel -configuration Release -destination 'generic/platform=macOS' \
    -derivedDataPath "$out" ARCHS=arm64 MARKETING_VERSION="$version" HEINZEL_MANAGED_INSTALL=YES \
    HEINZEL_SOURCE_REVISION="$revision" \
    HEINZEL_MAC_WIDGET_REFRESH="$widget_refresh" \
    HEINZEL_HTTPS_LINKS="$https_links" HEINZEL_ICLOUD_SIGN_IN="$cloud_sign_in" ${signing[@]+"${signing[@]}"} build -quiet
app="$stage/Heinzelmaennchen.app"
/usr/bin/ditto "$out/Build/Products/Release/Heinzel.app" "$app"
/usr/bin/codesign --verify --strict --deep "$app"
if [[ "$distribution" == developer-id ]]; then
    python3 scripts/verify-macos-developer-id.py "$app" "$HEINZEL_MAC_SIGNING_TEAM" "$version" "$revision"
    /usr/bin/ditto -c -k --keepParent "$app" "$stage/notarize.zip"
    xcrun notarytool submit "$stage/notarize.zip" --keychain-profile "$HEINZEL_MAC_NOTARY_PROFILE" \
        ${notary_keychain[@]+"${notary_keychain[@]}"} \
        --wait --timeout 20m --output-format json > "$stage/notary.json"
    # A successful submission is not an Accepted decision.
    [[ $(/usr/bin/plutil -extract status raw -o - "$stage/notary.json") == Accepted ]] || {
        printf '%s\n' 'Apple did not accept the Mac app for notarization.' >&2
        exit 1
    }
    xcrun stapler staple "$app"
fi
COPYFILE_DISABLE=1 /usr/bin/tar --format=pax --no-mac-metadata --no-xattrs --no-acls --no-fflags -czf "$candidate" \
    -C "$stage" Heinzelmaennchen.app
mkdir "$stage/verified"
/usr/bin/tar -xzf "$candidate" -C "$stage/verified"
/usr/bin/codesign --verify --strict --deep "$stage/verified/Heinzelmaennchen.app"
archived_links=$(/usr/bin/plutil -extract HeinzelHTTPSLinks raw -o - \
    "$stage/verified/Heinzelmaennchen.app/Contents/Info.plist")
if [[ "$archived_links" != "$https_links" ]]; then
    printf '%s\n' 'The archived app does not match HEINZEL_HTTPS_LINKS.' >&2
    exit 1
fi
archived_app="$stage/verified/Heinzelmaennchen.app"
archived_cloud=$(/usr/bin/plutil -extract HeinzelCloudSignIn raw -o - "$archived_app/Contents/Info.plist")
if [[ "$archived_cloud" != "$cloud_sign_in" ]]; then
    printf '%s\n' 'The archived app does not match HEINZEL_ICLOUD_SIGN_IN.' >&2
    exit 1
fi
if [[ "$cloud_sign_in" == YES || "$widget_refresh" == YES ]]; then
    python3 scripts/verify-macos-cloud.py "$archived_app" "$HEINZEL_MAC_SIGNING_TEAM" "$widget_refresh"
fi
if [[ "$distribution" == developer-id ]]; then
    python3 scripts/verify-macos-developer-id.py "$archived_app" "$HEINZEL_MAC_SIGNING_TEAM" "$version" "$revision"
    xcrun stapler validate "$archived_app"
    /usr/sbin/spctl --assess --type execute "$archived_app"
    if [[ -n ${GITHUB_STEP_SUMMARY:-} ]]; then
        submission=$(/usr/bin/plutil -extract id raw -o - "$stage/notary.json")
        [[ "$submission" =~ ^[A-Fa-f0-9]{8}(-[A-Fa-f0-9]{4}){3}-[A-Fa-f0-9]{12}$ ]]
        digest=$(/usr/bin/shasum -a 256 "$candidate")
        printf 'Swift v%s (%s), archive SHA-256 %s, notary submission %s Accepted. Extracted app and widget signatures, App Group, ticket and Gatekeeper verified.\n' \
            "$version" "$revision" "${digest%% *}" "$submission" >> "$GITHUB_STEP_SUMMARY"
    fi
fi
mv -f -- "$candidate" "$archive"
printf '%s\n' "$archive"
