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

cd "$(dirname "$0")"

echo "==> Stopping any running Pommedoro..."
pkill -9 -f Pommedoro 2>/dev/null || true
sleep 0.5

echo "==> Cleaning previous build..."
rm -rf .build/Pommedoro.app .build/Pommedoro.dmg

echo "==> Building DMG..."
make dmg

echo "==> Simulating download quarantine on DMG..."
xattr -w com.apple.quarantine "0081;67890abc;Safari;12345678-1234-1234-1234-123456789012" .build/Pommedoro.dmg

echo "==> Mounting quarantined DMG..."
hdiutil attach .build/Pommedoro.dmg -nobrowse -quiet

echo "==> Running Install.command from DMG..."
bash /Volumes/Pommedoro/Install.command

sleep 2

echo "==> Verifying app is running..."
if pgrep -x Pommedoro > /dev/null; then
    echo "==> SUCCESS: Pommedoro is running."
else
    echo "==> FAIL: Pommedoro did not launch."
    hdiutil detach /Volumes/Pommedoro -quiet 2>/dev/null || true
    exit 1
fi

echo "==> Verifying quarantine is stripped..."
if xattr /Applications/Pommedoro.app 2>&1 | grep -q "com.apple.quarantine"; then
    echo "==> FAIL: quarantine attribute still present."
    hdiutil detach /Volumes/Pommedoro -quiet 2>/dev/null || true
    exit 1
else
    echo "==> OK: no quarantine attribute."
fi

hdiutil detach /Volumes/Pommedoro -quiet 2>/dev/null || true

echo ""
echo "==> Done. DMG at: .build/Pommedoro.dmg"
