#!/bin/bash
# install-app-bundle.sh
# Creates a macOS App Bundle with environment validation.

# Set standard PATH for macOS (Homebrew, System Tools)
PATH="/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/homebrew/bin"

# --- Configuration ---
APP_NAME="MagicLinux"
BUNDLE_ID="com.andreas.magiclinux"
EXECUTABLE_NAME="magic-on-linux"
EXECUTABLE_PATH="build/$EXECUTABLE_NAME"
VERSION="1.1.0"

APP_ICON_SRC="assets/MagicOnLinux-Logo-512.jpg"
DOC_ICON_SRC="assets/atariprogram.png"

# --- Global Flags ---
DEBUG=false
INSTALL_LOCAL=false
INSTALL_SYSTEM=false
DO_CLEAN=false
DO_MAKE_CLEAN=false
SILENT=">/dev/null 2>&1"

# --- Functions ---

function show_help() {
    echo "Usage: bash $0 [OPTIONS]"
    echo ""
    echo "Options:"
    echo "  --install-local    Install (and overwrite) to ~/Applications"
    echo "  --install-system   Install (and overwrite) to /Applications (requires sudo)"
    echo "  --clean            Remove the local .app bundle"
    echo "  --make-clean       Execute 'make clean' in build directory"
    echo "  --debug            Enable debug mode"
    echo "  --help, --usage    Show this help message"
    exit 0
}

function fail() {
    echo "!! ERROR: $1" >&2
    exit 1
}

function check_dependencies() {
    local tools=("cmake" "make" "sips" "iconutil")
    for tool in "${tools[@]}"; do
        if ! command -v "$tool" &> /dev/null; then
            fail "Tool '$tool' not found."
        fi
    done
}

function perform_cleaning() {
    if [ "$DO_CLEAN" = true ]; then
        rm -rf "${APP_NAME}.app" || fail "Could not remove local bundle."
        echo "-> Local bundle removed."
    fi

    if [ "$DO_MAKE_CLEAN" = true ]; then
        if [ -d "build" ]; then
            echo "-> Cleaning build directory..."
            make -C build clean >/dev/null || echo "Note: make clean failed."
        fi
    fi
}

function build_executable() {
    if [ ! -f "$EXECUTABLE_PATH" ]; then
        echo "-> Starting build process ($EXECUTABLE_NAME)..."
        mkdir -p build
        pushd build >/dev/null || fail "Could not access build directory."
        
        if [ ! -f "Makefile" ]; then
            cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release .. >/dev/null || fail "CMake failed."
        fi
        
        if ! make >/dev/null 2>&1; then
            popd >/dev/null
            fail "Build failed. Run 'cd build && make' manually."
        fi
        popd >/dev/null
    fi
}

function create_icns() {
    local src=$1 out=$2 tmp_set="tmp.iconset"
    [ ! -f "$src" ] && fail "Icon source $src not found."
    rm -rf "$tmp_set" && mkdir -p "$tmp_set"
    
    local sizes=(16 32 128 256 512)
    for s in "${sizes[@]}"; do
        eval "sips -s format png -z $s $s \"$src\" --out \"${tmp_set}/icon_${s}x${s}.png\" $SILENT"
        double=$((s * 2))
        eval "sips -s format png -z $double $double \"$src\" --out \"${tmp_set}/icon_${s}x${s}@2x.png\" $SILENT"
    done
    
    eval "iconutil -c icns \"$tmp_set\" -o \"$out\" $SILENT" || fail "Icon generation failed."
    rm -rf "$tmp_set"
}

function assemble_bundle() {
    # If installation is requested, we always rebuild the bundle to be sure
    if [ "$INSTALL_LOCAL" = true ] || [ "$INSTALL_SYSTEM" = true ]; then
        rm -rf "${APP_NAME}.app"
    fi

    if [ ! -d "${APP_NAME}.app" ]; then
        build_executable
        echo "-> Assembling App Bundle..."
        mkdir -p "${APP_NAME}.app/Contents/MacOS"
        mkdir -p "${APP_NAME}.app/Contents/Resources"

        create_icns "$APP_ICON_SRC" "${APP_NAME}.app/Contents/Resources/AppIcon.icns"
        create_icns "$DOC_ICON_SRC" "${APP_NAME}.app/Contents/Resources/DocumentIcon.icns"
        
        cp "$EXECUTABLE_PATH" "${APP_NAME}.app/Contents/MacOS/"
        chmod +x "${APP_NAME}.app/Contents/MacOS/$EXECUTABLE_NAME"

        cat <<EOF > "${APP_NAME}.app/Contents/Info.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>CFBundleExecutable</key>
    <string>${EXECUTABLE_NAME}</string>
    <key>CFBundleIconFile</key>
    <string>AppIcon</string>
    <key>CFBundleIdentifier</key>
    <string>${BUNDLE_ID}</string>
    <key>CFBundleName</key>
    <string>${APP_NAME}</string>
    <key>CFBundlePackageType</key>
    <string>APPL</string>
    <key>CFBundleShortVersionString</key>
    <string>${VERSION}</string>
    <key>NSHighResolutionCapable</key>
    <true/>
</dict>
</plist>
EOF
        touch "${APP_NAME}.app"
    else
        echo "-> Existing App Bundle found. Use --clean to rebuild."
    fi
}

function perform_installation() {
    if [ "$INSTALL_LOCAL" = true ]; then
        local TARGET="$HOME/Applications/${APP_NAME}.app"
        echo "-> Installing to ~/Applications..."
        mkdir -p "$HOME/Applications"
        rm -rf "$TARGET" # Clean old version
        cp -Rp "${APP_NAME}.app" "$HOME/Applications/" && echo "-> Done."
    fi

    if [ "$INSTALL_SYSTEM" = true ]; then
        local TARGET="/Applications/${APP_NAME}.app"
        echo "-> Installing to /Applications (sudo)..."
        sudo rm -rf "$TARGET" # Clean old version
        sudo cp -Rp "${APP_NAME}.app" "/Applications/" && echo "-> Done."
    fi
}

# --- Main Execution Flow ---

for arg in "$@"; do
    case $arg in
        --debug) DEBUG=true; SILENT=""; set -x ;;
        --install-local) INSTALL_LOCAL=true ;;
        --install-system) INSTALL_SYSTEM=true ;;
        --clean) DO_CLEAN=true ;;
        --make-clean) DO_MAKE_CLEAN=true ;;
        --help|--usage) show_help ;;
        *) echo "Unknown option: $arg"; exit 1 ;;
    esac
done

check_dependencies
perform_cleaning

if { [ "$DO_CLEAN" = true ] || [ "$DO_MAKE_CLEAN" = true ]; } && \
   [ "$INSTALL_LOCAL" = false ] && [ "$INSTALL_SYSTEM" = false ]; then
    exit 0
fi

assemble_bundle
perform_installation

echo "Process completed successfully."