#!/bin/bash
#
# create-dmg packages the aws-vault CLI binary for macOS
# using Apple's signing and notorizing process
#
#
# As per https://developer.apple.com/documentation/security/notarizing_macos_software_before_distribution/customizing_the_notarization_workflow
# AC_PASSWORD can be set in your keychain with:
#     xcrun notarytool store-credentials "AC_PASSWORD"
#               --apple-id "AC_USERNAME"
#               --team-id <WWDRTeamID>
#               --password <secret_2FA_password>
#

set -euo pipefail

BIN_PATH="$1"
DMG_PATH="${2:-$1.dmg}"
CERT_ID="${CERT_ID:-"Developer ID Application: ByteNess Inc (R)"}"
KEYCHAIN_PROFILE="${KEYCHAIN_PROFILE:-AC_PASSWORD}"

if [[ -f "$DMG_PATH" ]] ; then
  echo "File '$DMG_PATH' already exists. Remove it and try again"
  exit 1
fi

tmpdir="$(mktemp -d)"
trap "rm -rf $tmpdir" EXIT

cp -a $BIN_PATH $tmpdir/aws-vault
src_path="$tmpdir/aws-vault"

echo "Signing binary"
codesign --options runtime --timestamp --sign "$CERT_ID" "$src_path"

echo "Creating dmg"
hdiutil create -quiet -srcfolder "$src_path" "$DMG_PATH"

echo "Signing dmg"
codesign --timestamp --sign "$CERT_ID" "$DMG_PATH"

echo "Submitting notorization request"
xcrun notarytool submit $DMG_PATH --keychain-profile "$KEYCHAIN_PROFILE" --wait

echo "Stapling"
xcrun stapler staple -q $DMG_PATH
