#!/bin/bash

# macOS post-build script for Raspberry Pi Imager
# This script creates a styled DMG for distribution

set -e

echo "Starting macOS post-build process..."

# Configuration
APP_NAME="@CMAKE_PROJECT_NAME@"
APP_PATH="@CMAKE_BINARY_DIR@/${APP_NAME}.app"
FINAL_DMG_PATH="@CMAKE_BINARY_DIR@/${APP_NAME}-@IMAGER_VERSION_STR@.dmg"
SIGNING_IDENTITY="@IMAGER_SIGNING_IDENTITY@"
SHOULD_NOTARIZE="@IMAGER_NOTARIZE_APP@"
KEYCHAIN_PROFILE="@IMAGER_NOTARIZE_KEYCHAIN_PROFILE@"

# Verify app bundle exists
if [ ! -d "$APP_PATH" ]; then
    echo "Error: App bundle not found at $APP_PATH"
    echo "Make sure the build completed successfully"
    exit 1
fi

echo "Found app bundle: $APP_PATH"

# Clean up any existing DMGs
echo "Cleaning up existing DMGs..."
rm -f "$FINAL_DMG_PATH"

# Create styled DMG using create-dmg
echo "Creating styled DMG..."
"@CMAKE_BINARY_DIR@/create_styled_dmg.sh" || {
    echo "Error: Failed to create styled DMG"
    exit 1
}

# Verify final DMG was created
if [ ! -f "$FINAL_DMG_PATH" ]; then
    echo "Error: Final DMG was not created at $FINAL_DMG_PATH"
    exit 1
fi

# Clean up any intermediate files
echo "Cleaning up intermediate build files..."
rm -f "@CMAKE_BINARY_DIR@"/temp_dmg_build*
rm -f "@CMAKE_BINARY_DIR@"/*.applescript
rm -f "@CMAKE_BINARY_DIR@"/dmg_*.html
rm -rf "@CMAKE_BINARY_DIR@"/dmg_temp*

# Clean up any background generation artifacts
rm -f "@CMAKE_CURRENT_SOURCE_DIR@/mac/dmg_background.html"

echo ""
echo "✅ macOS post-build process completed successfully!"
echo "Final DMG: $FINAL_DMG_PATH"
echo ""
echo "The DMG is ready for distribution and includes:"
if [ -n "$SIGNING_IDENTITY" ] && [ "$SIGNING_IDENTITY" != "NONE" ] && [ "$SIGNING_IDENTITY" != "" ]; then
    echo "  ✓ Code signing"
fi
if [ "$SHOULD_NOTARIZE" = "ON" ] && [ -n "$KEYCHAIN_PROFILE" ] && [ "$KEYCHAIN_PROFILE" != "" ]; then
    echo "  ✓ Notarization"
fi
echo ""
echo "Users can drag the app to Applications for easy installation!"

exit 0 