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

VERSION="${VERSION:-$(cat VERSION 2>/dev/null || echo 0.1.0-dev)}"
BUILD="${BUILD:-$(cat BUILD 2>/dev/null || echo 0)}"
APP_NAME="${APP_NAME:-AnotherEditor}"
APP_DIR="${APP_DIR:-release/${APP_NAME}.app}"
BINARY="${BINARY:-bin/anothereditor}"
ENTITLEMENTS="${ENTITLEMENTS:-packaging/macos/AnotherEditor.entitlements}"
MACOS_CODESIGN_IDENTITY="${MACOS_CODESIGN_IDENTITY:-}"
MACOS_NOTARY_PROFILE="${MACOS_NOTARY_PROFILE:-}"
MACOS_NOTARY_APPLE_ID="${MACOS_NOTARY_APPLE_ID:-}"
MACOS_NOTARY_PASSWORD="${MACOS_NOTARY_PASSWORD:-}"
MACOS_NOTARY_TEAM_ID="${MACOS_NOTARY_TEAM_ID:-}"

if [[ ! -x "${BINARY}" ]]; then
  echo "Application binary not found or not executable: ${BINARY}" >&2
  echo "Run 'make build' first." >&2
  exit 1
fi

rm -rf "${APP_DIR}"
mkdir -p "${APP_DIR}/Contents/MacOS" "${APP_DIR}/Contents/Resources"
cp -f "${BINARY}" "${APP_DIR}/Contents/MacOS/anothereditor"
cp -f packaging/macos/Info.plist "${APP_DIR}/Contents/Info.plist"
cp -f packaging/macos/anothereditor.icns "${APP_DIR}/Contents/Resources/anothereditor.icns"
cp -f packaging/linux/anothereditor.svg "${APP_DIR}/Contents/Resources/anothereditor.svg"
mkdir -p "${APP_DIR}/Contents/Resources/syntax"
cp -R syntax/grammars "${APP_DIR}/Contents/Resources/syntax/"

python3 - "${APP_DIR}/Contents/Info.plist" "${VERSION}" "${BUILD}" <<'PY'
import plistlib
import sys

path, version, build = sys.argv[1:]
with open(path, "rb") as fh:
    info = plistlib.load(fh)
info["CFBundleShortVersionString"] = version
info["CFBundleVersion"] = build
with open(path, "wb") as fh:
    plistlib.dump(info, fh)
PY
chmod +x "${APP_DIR}/Contents/MacOS/anothereditor"

if command -v codesign >/dev/null 2>&1; then
  if [[ -n "${MACOS_CODESIGN_IDENTITY}" ]]; then
    codesign --force --deep --options runtime --timestamp --entitlements "${ENTITLEMENTS}" --sign "${MACOS_CODESIGN_IDENTITY}" "${APP_DIR}"
  else
    codesign --force --deep --sign - "${APP_DIR}" >/dev/null 2>&1 || true
  fi
fi

if [[ -n "${MACOS_CODESIGN_IDENTITY}" ]] && command -v xcrun >/dev/null 2>&1; then
  NOTARY_ZIP="${APP_DIR%.app}-notary.zip"
  /usr/bin/ditto -c -k --keepParent "${APP_DIR}" "${NOTARY_ZIP}"
  if [[ -n "${MACOS_NOTARY_PROFILE}" ]]; then
    xcrun notarytool submit "${NOTARY_ZIP}" --keychain-profile "${MACOS_NOTARY_PROFILE}" --wait
    xcrun stapler staple "${APP_DIR}"
  elif [[ -n "${MACOS_NOTARY_APPLE_ID}" && -n "${MACOS_NOTARY_PASSWORD}" && -n "${MACOS_NOTARY_TEAM_ID}" ]]; then
    xcrun notarytool submit "${NOTARY_ZIP}" --apple-id "${MACOS_NOTARY_APPLE_ID}" --password "${MACOS_NOTARY_PASSWORD}" --team-id "${MACOS_NOTARY_TEAM_ID}" --wait
    xcrun stapler staple "${APP_DIR}"
  fi
fi

echo "Built ${APP_DIR}"
