#!/bin/bash
set -euo pipefail

REPO="$(cd "$(dirname "$0")" && pwd)/build"
APP="$HOME/Applications/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 installed at: $APP"
