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

cd "$(dirname "$0")/.."

if [ "$(uname -s)" != "Darwin" ]; then
  echo "This script only supports macOS (Darwin)."
  exit 1
fi

if ! command -v hdiutil >/dev/null 2>&1; then
  echo "hdiutil not found. This script requires macOS disk image tools."
  exit 1
fi

if [ "${REBUILD_APP:-0}" = "1" ]; then
  ./scripts/build_macos_app.sh
fi

APP_NAME="${EKSAMENAPP_APP_NAME:-ATHENODE}"
APP_BUNDLE="dist/${APP_NAME}.app"

if [ ! -d "${APP_BUNDLE}" ]; then
  echo "App bundle not found at ${APP_BUNDLE}."
  echo "Run ./scripts/build_macos_app.sh first (or set REBUILD_APP=1)."
  exit 1
fi

STAMP="$(date +%Y%m%d_%H%M%S)"
ARCH_NAME="$(uname -m | tr '[:upper:]' '[:lower:]')"
PACKAGE_NAME="${1:-athenode_macos_${ARCH_NAME}_${STAMP}}"
DMG_PATH="dist/${PACKAGE_NAME}.dmg"

STAGE_DIR="$(mktemp -d)"
cleanup() {
  rm -rf "${STAGE_DIR}"
}
trap cleanup EXIT

cp -R "${APP_BUNDLE}" "${STAGE_DIR}/${APP_NAME}.app"
ln -s /Applications "${STAGE_DIR}/Applications"

hdiutil create \
  -volname "${APP_NAME}" \
  -srcfolder "${STAGE_DIR}" \
  -ov \
  -fs HFS+ \
  -format UDZO \
  "${DMG_PATH}" || {
    echo "[WARN] hdiutil failed. Creating ZIP fallback with the .app bundle."
    ZIP_PATH="dist/${PACKAGE_NAME}.zip"
    ditto -c -k --sequesterRsrc --keepParent "${STAGE_DIR}/${APP_NAME}.app" "${ZIP_PATH}"
    if command -v shasum >/dev/null 2>&1; then
      shasum -a 256 "${ZIP_PATH}" > "${ZIP_PATH}.sha256"
    fi
    echo "Created fallback app ZIP: ${ZIP_PATH}"
    if [ -f "${ZIP_PATH}.sha256" ]; then
      echo "Created checksum: ${ZIP_PATH}.sha256"
    fi
    exit 0
  }

if command -v shasum >/dev/null 2>&1; then
  shasum -a 256 "${DMG_PATH}" > "${DMG_PATH}.sha256"
fi

echo "Created macOS DMG: ${DMG_PATH}"
if [ -f "${DMG_PATH}.sha256" ]; then
  echo "Created checksum: ${DMG_PATH}.sha256"
fi
