#!/usr/bin/env bash
set -e

# See https://developer.apple.com/documentation/technotes/tn3147-migrating-to-the-latest-notarization-tool

# App specific password and credentials used to request notarization
password_path="$HOME/.ssh/apple-notarization-password"
apple_id_path="$HOME/.ssh/apple-id"
team_id_path="$HOME/.ssh/apple-team-id"

if test -f "$password_path" ; then
  app_specific_password=`cat "$password_path"`
else
  echo "\"$password_path\" does not exist"
  exit 1
fi
if test -f "$apple_id_path" ; then
  apple_id=`cat "$apple_id_path"`
else
  echo "\"$apple_id_path\" does not exist"
  exit 1
fi
if test -f "$team_id_path" ; then
  team_id=`cat "$team_id_path"`
else
  echo "\"$team_id_path\" does not exist"
  exit 1
fi

pkg="$1"
pkgname="$2"

echo "Notarize request"
xcrun notarytool submit \
  --wait \
  --apple-id "$apple_id" \
  --team-id "$team_id" \
  --password "$app_specific_password" \
  "$pkg"

# this should end with something like
#Processing complete
#  id: 87c2e5e9-f37f-4a95-9941-8c2205fc90bd
#  status: Accepted

# At this point the software can be installed. However it is recommended
# to staple the pkg file
# so that Gatekeeper will be able to find the whitelist in the file itself
# without the need to perform an online check.
xcrun stapler staple "$pkg"

# Lastly, copy the pkg file to its proper name in $HOME

# I've read that it is a good idea to check for warnings by
# fetching the notary log (using the id generated by the above submit)
# And if there are errors, then you certainly need to fetch the log,
# address the issues it shows and try again.
if false ; then
  xcrun notarytool log \
    --apple-id "$apple_id" \
    --team-id "$team_id" \
    --password "$app_specific_password" \
    "$id"
fi

# To get a history of notarizations...
if false ; then
  xcrun notarytool history \
    --apple-id "$apple_id" \
    --team-id "$team_id" \
    --password "$app_specific_password"
fi
