#!/bin/bash
set -euo pipefail

REPO="$(cd "$(dirname "$0")" && pwd)/build"
APP="./out/Photon Uploader.app"
CONTENTS="$APP/Contents"

echo "==> Building PhotonUploader (menu bar binary)..."
swiftc -framework AppKit \
    "$REPO/PhotonUploader/main.swift" \
    -o "$REPO/PhotonUploader/upload"

echo "==> Building PhotonNotify (notification helper)..."
swiftc -framework Foundation -framework UserNotifications -framework AppKit \
    "$REPO/PhotonNotify/main.swift" \
    -o "$REPO/PhotonNotify/PhotonNotify"

echo "==> Assembling app bundle..."
mkdir -p "$CONTENTS/MacOS"
mkdir -p "$CONTENTS/Resources"
mkdir -p "$CONTENTS/Helpers/PhotonNotify.app/Contents/MacOS"
mkdir -p "$CONTENTS/Helpers/PhotonNotify.app/Contents/Resources"

cp "$REPO/PhotonUploader/upload"          "$CONTENTS/MacOS/upload"
cp "$REPO/upload.sh"                      "$CONTENTS/MacOS/upload.sh"
cp "$REPO/Info.plist"                     "$CONTENTS/Info.plist"

cp "$REPO/PhotonNotify/PhotonNotify"      "$CONTENTS/Helpers/PhotonNotify.app/Contents/MacOS/PhotonNotify"
cp "$REPO/PhotonNotify/Info.plist"        "$CONTENTS/Helpers/PhotonNotify.app/Contents/Info.plist"
cp "$REPO/Resources/AppIcon.icns"         "$CONTENTS/Helpers/PhotonNotify.app/Contents/Resources/AppIcon.icns"

cp "$REPO/Resources/AppIcon.icns"         "$CONTENTS/Resources/AppIcon.icns"
cp "$REPO/Resources/MenuBarIcon.png"      "$CONTENTS/Resources/MenuBarIcon.png"
cp "$REPO/Resources/MenuBarIcon@2x.png"   "$CONTENTS/Resources/MenuBarIcon@2x.png"

chmod +x "$CONTENTS/MacOS/upload"
chmod +x "$CONTENTS/MacOS/upload.sh"
chmod +x "$CONTENTS/Helpers/PhotonNotify.app/Contents/MacOS/PhotonNotify"

echo "==> Signing..."
codesign --force --sign - "$CONTENTS/Helpers/PhotonNotify.app"
codesign --force --sign - "$APP"

echo "==> Done. App bundle at: $APP"

echo "==> Creating DMG..."
DMG_STAGING="./out/dmg-staging"
DMG_OUT="./out/Photon Uploader.dmg"

if ! command -v create-dmg &>/dev/null; then
    echo "Error: create-dmg is not installed. Run: brew install create-dmg" >&2
    exit 1
fi

rm -rf "$DMG_STAGING"
mkdir -p "$DMG_STAGING"
cp -r "$APP" "$DMG_STAGING/"

rm -f "$DMG_OUT"
create-dmg \
    --volname "Photon Uploader" \
    --volicon "$REPO/Resources/AppIcon.icns" \
    --window-pos 200 120 \
    --window-size 540 380 \
    --icon-size 96 \
    --icon "Photon Uploader.app" 140 190 \
    --hide-extension "Photon Uploader.app" \
    --app-drop-link 400 190 \
    "$DMG_OUT" \
    "$DMG_STAGING"

rm -rf "$DMG_STAGING"
echo "==> Done. DMG at: $DMG_OUT"
