#!/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
    if [[ "$distribution" == development ]]; then
        signing+=("CODE_SIGN_STYLE=Manual" "CODE_SIGN_IDENTITY=Apple Development" "HEINZEL_APS_ENVIRONMENT=development")
    else
        # Developer ID: the profile's application identifier is named explicitly, nothing is injected.
        signing+=("HEINZEL_MAC_WIDGET_ENTITLEMENTS=Widgets/MacWidgetGroupCloud.entitlements")
    fi
    signing+=("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
    # iCloud sign-in needs the Developer ID provisioning profiles; without it, no profile may be embedded.
    if [[ ! ${HEINZEL_MAC_SIGNING_TEAM:-} =~ ^[A-Z0-9]{10}$ ||
          -z ${HEINZEL_MAC_NOTARY_PROFILE:-} || "$widget_refresh" != NO ||
          ( "$cloud_sign_in" == NO && ( -n ${HEINZEL_MAC_PROFILE:-} || -n ${HEINZEL_MAC_WIDGET_PROFILE:-} ) ) ]]; then
        printf '%s\n' 'Developer ID requires a signing Team and notary profile, and app profiles only for iCloud sign-in.' >&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)
app="$stage/Heinzelmaennchen.app"
# A resumed notarization (HEINZEL_MAC_NOTARY_RESUME) continues with the signed bytes an earlier job submitted:
# no rebuild, no second signature, no second submission (apple/scripts/notary.py).
resume=${HEINZEL_MAC_NOTARY_RESUME:-}
if [[ -n "$resume" ]]; then
    if [[ "$distribution" != developer-id || ! -f "$resume/notarize.zip" || ! -f "$resume/notary.json" ]]; then
        printf '%s\n' 'A notarization resume needs a Developer ID build and its recorded submission.' >&2
        exit 2
    fi
    /usr/bin/ditto -x -k "$resume/notarize.zip" "$stage"
else
    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
    /usr/bin/ditto "$out/Build/Products/Release/Heinzel.app" "$app"
fi
/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" \
        --cloud-sign-in "$cloud_sign_in"
    if [[ -n "$resume" ]]; then
        cp -- "$resume/notarize.zip" "$resume/notary.json" "$stage/"
    else
        /usr/bin/ditto -c -k --keepParent "$app" "$stage/notarize.zip"
    fi
    # The submission id is recorded before any wait; a wait past its budget keeps the signed bytes and the record
    # (HEINZEL_MAC_NOTARY_PENDING) and exits 75, so a later job waits for the same submission.
    python3 scripts/notary.py submit "$stage/notarize.zip" --record "$stage/notary.json" \
        --keychain-profile "$HEINZEL_MAC_NOTARY_PROFILE" ${notary_keychain[@]+"${notary_keychain[@]}"} >/dev/null
    notarized=0
    python3 scripts/notary.py wait --record "$stage/notary.json" --budget "${HEINZEL_MAC_NOTARY_BUDGET:-1500}" \
        --keychain-profile "$HEINZEL_MAC_NOTARY_PROFILE" ${notary_keychain[@]+"${notary_keychain[@]}"} || notarized=$?
    if [[ $notarized == 75 && -n ${HEINZEL_MAC_NOTARY_PENDING:-} ]]; then
        mkdir -p -- "$HEINZEL_MAC_NOTARY_PENDING"
        cp -- "$stage/notarize.zip" "$stage/notary.json" "$HEINZEL_MAC_NOTARY_PENDING/"
    fi
    if [[ $notarized != 0 ]]; then
        exit "$notarized"
    fi
    # 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" "$distribution"
fi
if [[ "$distribution" == developer-id ]]; then
    python3 scripts/verify-macos-developer-id.py "$archived_app" "$HEINZEL_MAC_SIGNING_TEAM" "$version" "$revision" \
        --cloud-sign-in "$cloud_sign_in"
    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. iCloud sign-in: %s.\n' \
            "$version" "$revision" "${digest%% *}" "$submission" "$cloud_sign_in" >> "$GITHUB_STEP_SUMMARY"
    fi
fi
mv -f -- "$candidate" "$archive"
printf '%s\n' "$archive"
