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

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
DIST_DIR="$SCRIPT_DIR"

# Parse flags
SKIP_NOTARIZE=false
for arg in "$@"; do
    case "$arg" in
        --skip-notarize) SKIP_NOTARIZE=true ;;
        *) echo "Unknown flag: $arg"; echo "Usage: $0 [--skip-notarize]"; exit 1 ;;
    esac
done

# Read version from Cargo.toml
VERSION=$(grep '^version' "$PROJECT_DIR/crates/audiofiles-app/Cargo.toml" | head -1 | sed 's/.*"\(.*\)".*/\1/')
echo "Building AudioFiles v${VERSION}"

ARCH=$(uname -m)
APP_BUNDLE="$DIST_DIR/AudioFiles.app"
DMG_NAME="AudioFiles_${VERSION}_${ARCH}.dmg"
DMG_PATH="$DIST_DIR/$DMG_NAME"
SIGNING_IDENTITY="Developer ID Application: MAXWELL MORGAN JOHNSON (93C54W92UP)"
NOTARY_PROFILE="notarytool-profile"

# Step 1: Build release binary
echo "==> Building release binary..."
cd "$PROJECT_DIR"
cargo build --release -p audiofiles-app

# Step 2: Assemble app bundle
echo "==> Assembling app bundle..."
rm -rf "$APP_BUNDLE"
mkdir -p "$APP_BUNDLE/Contents/MacOS"
mkdir -p "$APP_BUNDLE/Contents/Resources"

cp "$PROJECT_DIR/target/release/audiofiles-app" "$APP_BUNDLE/Contents/MacOS/audiofiles-app"
cp "$PROJECT_DIR/crates/audiofiles-app/AppIcon.icns" "$APP_BUNDLE/Contents/Resources/AppIcon.icns"

# Patch Info.plist with current version
sed -e "s|<string>0\.[0-9]*\.[0-9]*</string><!-- CFBundleVersion -->|<string>${VERSION}</string><!-- CFBundleVersion -->|" \
    "$DIST_DIR/Info.plist.template" > "$APP_BUNDLE/Contents/Info.plist" 2>/dev/null || true

# If template doesn't exist, write Info.plist directly with current version
if [ ! -f "$APP_BUNDLE/Contents/Info.plist" ] || [ ! -s "$APP_BUNDLE/Contents/Info.plist" ]; then
    cat > "$APP_BUNDLE/Contents/Info.plist" << PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleName</key>
    <string>AudioFiles</string>
    <key>CFBundleIdentifier</key>
    <string>com.audiofiles.app</string>
    <key>CFBundleVersion</key>
    <string>${VERSION}</string>
    <key>CFBundleShortVersionString</key>
    <string>${VERSION}</string>
    <key>CFBundleExecutable</key>
    <string>audiofiles-app</string>
    <key>CFBundleIconFile</key>
    <string>AppIcon</string>
    <key>CFBundlePackageType</key>
    <string>APPL</string>
    <key>NSHighResolutionCapable</key>
    <true/>
    <key>CFBundleDocumentTypes</key>
    <array>
        <dict>
            <key>CFBundleTypeName</key>
            <string>Audio File</string>
            <key>CFBundleTypeRole</key>
            <string>Viewer</string>
            <key>LSHandlerRank</key>
            <string>Alternate</string>
            <key>CFBundleTypeExtensions</key>
            <array>
                <string>wav</string>
                <string>flac</string>
                <string>mp3</string>
                <string>ogg</string>
                <string>aiff</string>
                <string>aif</string>
            </array>
        </dict>
    </array>
</dict>
</plist>
PLIST
fi

# Step 3: Code sign the app bundle
echo "==> Signing app bundle..."
codesign --deep --force --options runtime \
    --sign "$SIGNING_IDENTITY" \
    "$APP_BUNDLE"

echo "==> Verifying signature..."
codesign --verify --deep --strict "$APP_BUNDLE"

# Step 4: Create DMG
echo "==> Creating DMG..."
rm -f "$DMG_PATH"

DMG_STAGING="$DIST_DIR/.dmg-staging"
rm -rf "$DMG_STAGING"
mkdir -p "$DMG_STAGING"
cp -R "$APP_BUNDLE" "$DMG_STAGING/"
ln -s /Applications "$DMG_STAGING/Applications"

hdiutil create -volname "AudioFiles" \
    -srcfolder "$DMG_STAGING" \
    -ov -format UDZO \
    "$DMG_PATH"

rm -rf "$DMG_STAGING"

# Step 5: Sign the DMG
echo "==> Signing DMG..."
codesign --force --sign "$SIGNING_IDENTITY" "$DMG_PATH"

if [ "$SKIP_NOTARIZE" = true ]; then
    echo "==> Skipping notarization (--skip-notarize)"
    echo ""
    echo "Done: $DMG_PATH"
    exit 0
fi

# Step 6: Notarize
echo "==> Notarizing DMG..."
xcrun notarytool submit "$DMG_PATH" \
    --keychain-profile "$NOTARY_PROFILE" \
    --wait

# Step 7: Staple
echo "==> Stapling notarization ticket..."
xcrun stapler staple "$DMG_PATH"

echo ""
echo "Done: $DMG_PATH"
