#!/bin/bash
set -e

cd $(dirname $0)/..

: ${KEYCHAIN="build.keychain"}
: ${SIGN=""}
: ${NOTARIZE=""}
: ${AC_BUNDLE="io.acorn.cli"}

BINARY="$1"
DIR="releases/mac_darwin_all"
DMG="releases/$2.dmg"
CHECKSUMS="releases/checksums.txt"

if [[ -z "${SIGN}" && "$(uname)" == "Darwin" ]]; then
  SIGN="1"
fi

if [[ -z "${NOTARIZE}" && "$(uname)" == "Darwin" && "${GITHUB_REF}" =~ "refs/tags/v" ]]; then
  echo "Enabling notarize"
  NOTARIZE="1"
fi

echo "SIGN=${SIGN} NOTARIZE=${NOTARIZE} BUNDLE=${AC_BUNDLE} BINARY=${BINARY} DMG=${DMG}"

if [[ "${SIGN}" == 1 ]]; then
  echo "Signing"

  echo "${AC_P12}" | base64 --decode > signing.p12
  security import signing.p12 -P "${AC_P12_PASSWORD}" -A -t cert -f pkcs12 -k $KEYCHAIN || true

  codesign -s "${AC_IDENTITY}" -f -v --timestamp --options runtime "${BINARY}"
else
  echo "Skipping signing"
  exit 0
fi

if [[ "${SIGN}" == 1 && "${NOTARIZE}" == 1 ]]; then
  echo "Notarizing…"

  cp LICENSE README.md "${DIR}/"
  hdiutil create -volname "Acorn" -size 1g -srcfolder "${DIR}" -ov -format UDZO "${DMG}"
  which gon || (go install github.com/mitchellh/gon/cmd/gon@latest)

  cat <<EOF > "gon.hcl"
notarize {
  path = "${DMG}"
  bundle_id = "${AC_BUNDLE}"
  staple = true
}
EOF

  gon gon.hcl
  shasum -a 256 "${DMG}" >> "${CHECKSUMS}"

  rm gon.hcl
else
  echo "Skipping notarizing & disk image creation"
fi

