#!/bin/bash

set -e

script_dir=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
source "$script_dir/functions"
source "$script_dir/set-config.rcodesign-appstoreconnect"

test -d "$macos_rcodesign_signed_tar_dir" || \
  exit_error "The signed macos tar files should be placed in directory $macos_rcodesign_signed_tar_dir"

test -f "$appstoreconnect_api_key_path" || \
  exit_error "$appstoreconnect_api_key_path is missing. See this page for how to create it: https://gregoryszorc.com/docs/apple-codesign/main/apple_codesign_getting_started.html#apple-codesign-app-store-connect-api-key"

"$script_dir/setup-rcodesign"

tmpdir=$(mktemp -d -p /var/tmp)
trap "rm -Rf $tmpdir" EXIT

display_name=$(display_name)

tar -C "$tmpdir" -xf "$macos_rcodesign_signed_tar_dir/$(project-name)-macos-${tbb_version}-rcodesign-signed.tar.zst"

"$script_dir/../local/rcodesign-128/rcodesign" notary-submit --max-wait-seconds 6000 --api-key-path "$appstoreconnect_api_key_path" --staple "$tmpdir/$display_name.app"

output_file="$(project-name)-${tbb_version}-notarized+stapled.tar.zst"
tar -C "$tmpdir" -caf "$tmpdir/$output_file" "$display_name.app"
mkdir -p "$macos_stapled_dir"
mv "$tmpdir/$output_file" "$macos_stapled_dir/$output_file"

rm -Rf "$tmpdir"
