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

# This script has two modes:
# script/notarize-mac sign_binary <binary_path>
# script/notarize-mac sign_app_binaries <bundle_name> <target_dir> <channel> <app_path> <architecture> <architecture_dir>
#
# The first mode sign and notarizes a binary (e.g. zed-remote-server)
# The second mode takes a an app bundle, signs and notarizes it,
#   then builds a DMG containing that app and signs and notarizes that.
#

# this function is called from the bottom of the script.
function handle_args() {
    if [[ -z "${local_only:-}" ]]; then
        echo "Error: 'local_only' is not set in the environment."
        echo "This script should not be called directly and only invoked from script/bundle-mac."
        exit 1
    elif [ "$1" = "sign_binary" ] && [ $# -eq 2 ]; then
        setup_keychains
        sign_binary "$2"
    elif [ "$1" = "sign_app_binaries" ] && [ $# -eq 7 ]; then
        setup_keychains
        sign_app_binaries "$2" "$3" "$4" "$5" "$6" "$7"
    else
        echo "Usage: $0 sign_binary <binary_path>"
        echo "   or: $0 sign_app_binaries <bundle_name> <target_dir> <channel> <app_path> <architecture> <architecture_dir>"
        exit 1
    fi
}

# Create temporary keychains used for signing.
function setup_keychains() {
    # Identity/TeamID must match what is specified in the provisioning profile.
    IDENTITY="Zed Industries, Inc."
    APPLE_NOTORIZATION_TEAM="MQ55VZLNZQ"
    if [[ -n "${MACOS_CERTIFICATE:-}" \
        && -n "${MACOS_CERTIFICATE_PASSWORD:-}" \
        && -n "${APPLE_NOTARIZATION_USERNAME:-}" \
        && -n "${APPLE_NOTARIZATION_PASSWORD:-}" ]]
    then
        can_code_sign=true
        echo "Setting up keychain for code signing..."
        security create-keychain -p "$MACOS_CERTIFICATE_PASSWORD" zed.keychain || echo ""
        security default-keychain -s zed.keychain
        security unlock-keychain -p "$MACOS_CERTIFICATE_PASSWORD" zed.keychain
        echo "$MACOS_CERTIFICATE" | base64 --decode > /tmp/zed-certificate.p12
        security import /tmp/zed-certificate.p12 -k zed.keychain -P "$MACOS_CERTIFICATE_PASSWORD" -T /usr/bin/codesign
        rm /tmp/zed-certificate.p12
        security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$MACOS_CERTIFICATE_PASSWORD" zed.keychain

        # shellcheck disable=SC2317
        function cleanup() {
            echo "Cleaning up keychain"
            security default-keychain -s login.keychain
            security delete-keychain zed.keychain
        }

        trap cleanup EXIT
    else
        can_code_sign=false
    fi
}

# Signs and notarizes a binary at $1
function sign_binary() {
    local binary_path=$1
    if [[ $can_code_sign = true ]]; then
        echo "Code signing executable $binary_path"
        /usr/bin/codesign --deep --force --timestamp --options runtime \
          --entitlements crates/zed/resources/zed.entitlements \
          --sign "$IDENTITY" "${binary_path}" -v
    fi
}

# app bundle: sign, notarize; then build dmg and sign, notarize
function sign_app_binaries() {
    local bundle_name=$1
    local target_dir=$2
    local channel=$3
    local app_path=$4
    local architecture=$5
    local architecture_dir=$6
    echo "Copying WebRTC.framework into the frameworks folder"
    mkdir "${app_path}/Contents/Frameworks"
    if [ "$local_only" = false ]; then
        cp -R "target/${architecture}/${target_dir}/WebRTC.framework" "${app_path}/Contents/Frameworks/"
    else
        cp -R "target/${target_dir}/WebRTC.framework" "${app_path}/Contents/Frameworks/"
        cp -R "target/${target_dir}/cli" "${app_path}/Contents/MacOS/"
    fi

    # Note: The app identifier for our development builds is the same as the app identifier for nightly.
    cp "crates/zed/contents/$channel/embedded.provisionprofile" "${app_path}/Contents/"

    if [[ $can_code_sign = true ]]; then
        echo "Code signing binaries"
        # sequence of codesign commands modeled after this example: https://developer.apple.com/forums/thread/701514
        /usr/bin/codesign --deep --force --timestamp --sign "$IDENTITY" "${app_path}/Contents/Frameworks/WebRTC.framework" -v
        /usr/bin/codesign --deep --force --timestamp --options runtime --sign "$IDENTITY" "${app_path}/Contents/MacOS/cli" -v
        /usr/bin/codesign --deep --force --timestamp --options runtime --sign "$IDENTITY" "${app_path}/Contents/MacOS/git" -v
        /usr/bin/codesign --deep --force --timestamp --options runtime \
            --entitlements crates/zed/resources/zed.entitlements \
            --sign "$IDENTITY" "${app_path}/Contents/MacOS/zed" -v
        /usr/bin/codesign --force --timestamp --options runtime \
            --entitlements crates/zed/resources/zed.entitlements \
            --sign "$IDENTITY" "${app_path}" -v
    else
        echo "One or more of the following variables are missing: MACOS_CERTIFICATE, MACOS_CERTIFICATE_PASSWORD, APPLE_NOTARIZATION_USERNAME, APPLE_NOTARIZATION_PASSWORD"

        echo "====== WARNING ======"
        echo "This bundle is being signed without all entitlements, some features (e.g. universal links) will not work"
        echo "====== WARNING ======"

        # NOTE: if you need to test universal links you have a few paths forward:
        # - create a PR and tag it with the `run-bundling` label, and download the .dmg file from there.
        # - get a signing key for the MQ55VZLNZQ team from Nathan.
        # - create your own signing key, and update references to MQ55VZLNZQ to your own team ID
        # then comment out this line.
        sed '/com.apple.developer.associated-domains/,+1d' \
            crates/zed/resources/zed.entitlements \
            > "${app_path}/Contents/Resources/zed.entitlements"

        codesign --force --deep \
            --entitlements "${app_path}/Contents/Resources/zed.entitlements" \
            --sign "${MACOS_SIGNING_KEY:- -}" "${app_path}" -v

        echo "Created application bundle:"
        echo "$app_path"
    fi


    dmg_target_directory="target/${architecture_dir}/${target_dir}"
    dmg_source_directory="${dmg_target_directory}/dmg"
    dmg_file_path="${dmg_target_directory}/Zed.dmg"
    xcode_bin_dir_path="$(xcode-select -p)/usr/bin"

    rm -rf "${dmg_source_directory}"
    mkdir -p "${dmg_source_directory}"
    mv "${app_path}" "${dmg_source_directory}"

    if [[ $can_code_sign = true ]]; then
        echo "Creating temporary DMG at ${dmg_file_path} using ${dmg_source_directory} to notarize app bundle"
        hdiutil create -volname Zed -srcfolder "${dmg_source_directory}" -ov -format UDZO "${dmg_file_path}"

        echo "Code-signing DMG"
        /usr/bin/codesign --deep --force --timestamp --options runtime --sign "$IDENTITY" "$(pwd)/${dmg_file_path}" -v

        echo "Notarizing DMG with Apple"
        "${xcode_bin_dir_path}/notarytool" submit --wait --apple-id "$APPLE_NOTARIZATION_USERNAME" --password "$APPLE_NOTARIZATION_PASSWORD" --team-id "$APPLE_NOTORIZATION_TEAM" "${dmg_file_path}"

        echo "Removing temporary DMG (used only for notarization)"
        rm "${dmg_file_path}"

        echo "Stapling notarization ticket to ${dmg_source_directory}/${bundle_name}"
        "${xcode_bin_dir_path}/stapler" staple "${dmg_source_directory}/${bundle_name}"
    fi

    echo "Adding symlink to /Applications to ${dmg_source_directory}"
    ln -s "/Applications" "${dmg_source_directory}"

    echo "Creating final DMG at ${dmg_file_path} using ${dmg_source_directory}"
    hdiutil create -volname Zed -srcfolder "${dmg_source_directory}" -ov -format UDZO "${dmg_file_path}"

    # If someone runs this bundle script locally, a symlink will be placed in `dmg_source_directory`.
    # This symlink causes CPU issues with Zed if the Zed codebase is the project being worked on, so we simply remove it for now.
    echo "Removing symlink to /Applications from ${dmg_source_directory}"
    rm "${dmg_source_directory}/Applications"

    echo "Adding license agreement to DMG"
    npm install --global dmg-license minimist
    dmg-license script/terms/terms.json "${dmg_file_path}"

    if [[ $can_code_sign = true ]]; then
        echo "Notarizing DMG with Apple"
        /usr/bin/codesign --deep --force --timestamp --options runtime --sign "$IDENTITY" "$(pwd)/${dmg_file_path}" -v
        "${xcode_bin_dir_path}/notarytool" submit --wait --apple-id "$APPLE_NOTARIZATION_USERNAME" --password "$APPLE_NOTARIZATION_PASSWORD" --team-id "$APPLE_NOTORIZATION_TEAM" "${dmg_file_path}"
        "${xcode_bin_dir_path}/stapler" staple "${dmg_file_path}"
    fi
}


# do the things
handle_args "$@"
