#!/usr/bin/env bash
# Install the optional Developer ID provisioning profiles for iCloud sign-in and print the packaging settings.
# Both profiles enable iCloud sign-in; neither keeps it off with a stated reason; only one is a configuration error.
set -euo pipefail
umask 077
app_profile=${HEINZEL_MAC_APP_PROFILE_B64:-}
widget_profile=${HEINZEL_MAC_WIDGET_PROFILE_B64:-}
scratch=${1:?Usage: install-macos-cloud-profiles SCRATCH_DIR}
if [[ -z "$app_profile" && -z "$widget_profile" ]]; then
    reason='iCloud sign-in is off: no Developer ID provisioning profiles (HEINZEL_MAC_APP_PROFILE_B64, HEINZEL_MAC_WIDGET_PROFILE_B64).'
    printf '::warning::%s\n' "$reason" >&2
    if [[ -n ${GITHUB_STEP_SUMMARY:-} ]]; then printf '%s\n' "$reason" >> "$GITHUB_STEP_SUMMARY"; fi
    printf '%s\n' HEINZEL_ICLOUD_SIGN_IN=NO
    exit 0
fi
if [[ -z "$app_profile" || -z "$widget_profile" ]]; then
    printf '%s\n' 'iCloud sign-in needs both Developer ID provisioning profiles: the app and the widget.' >&2
    exit 2
fi
install_profile() {
    local encoded=$1 name=$2 file uuid folder
    file="$scratch/$name.provisionprofile"
    printf '%s' "$encoded" | /usr/bin/base64 -D > "$file"
    /usr/bin/security cms -D -i "$file" > "$scratch/$name.plist"
    uuid=$(/usr/bin/plutil -extract UUID raw -o - "$scratch/$name.plist")
    [[ "$uuid" =~ ^[A-Fa-f0-9]{8}(-[A-Fa-f0-9]{4}){3}-[A-Fa-f0-9]{12}$ ]] || {
        printf 'The %s provisioning profile has no valid UUID.\n' "$name" >&2
        exit 2
    }
    # Xcode 16 and later read the first folder, earlier versions the second.
    for folder in "$HOME/Library/Developer/Xcode/UserData/Provisioning Profiles" \
                  "$HOME/Library/MobileDevice/Provisioning Profiles"; do
        mkdir -p "$folder"
        cp -- "$file" "$folder/$uuid.provisionprofile"
    done
    printf '%s' "$uuid"
}
app_uuid=$(install_profile "$app_profile" app)
widget_uuid=$(install_profile "$widget_profile" widget)
printf '%s\n' HEINZEL_ICLOUD_SIGN_IN=YES "HEINZEL_MAC_PROFILE=$app_uuid" "HEINZEL_MAC_WIDGET_PROFILE=$widget_uuid"
