#!/bin/bash

# =========================
# Installation Script Configuration
# =========================
APP_NAME="Elgato Reporter.app"                    # Target app name to install
SRC="$(dirname "$0")/../Resources/$APP_NAME"      # Source path (embedded in installer)
DEST="/Applications/$APP_NAME"                    # Destination path (standard macOS location)

# =========================
# Version Comparison Function
# =========================
# Compare version numbers supporting both 3-part and 4-part formats
version_compare() {
    local ver1=$1  # Current installed version
    local ver2=$2  # Installer version
    
    # Convert versions to zero-padded comparable format
    ver1_num=$(echo "$ver1" | awk -F. '{ 
        if (NF == 3) printf("%03d%03d%03d000\n", $1,$2,$3); 
        else if (NF == 4) printf("%03d%03d%03d%03d\n", $1,$2,$3,$4);
        else printf("%03d000000000\n", $1);
    }')
    ver2_num=$(echo "$ver2" | awk -F. '{ 
        if (NF == 3) printf("%03d%03d%03d000\n", $1,$2,$3); 
        else if (NF == 4) printf("%03d%03d%03d%03d\n", $1,$2,$3,$4);
        else printf("%03d000000000\n", $1);
    }')
    
    # Return comparison result
    if [ "$ver1_num" -gt "$ver2_num" ]; then
        echo "greater"    # Current version is newer
    elif [ "$ver1_num" -eq "$ver2_num" ]; then
        echo "equal"      # Same version
    else
        echo "lesser"     # Installer version is newer
    fi
}

# =========================
# Installation Process
# =========================
echo "Installing $APP_NAME to /Applications..."

# Extract version from the installer package
INSTALLER_VERSION=$(grep -A1 '<key>CFBundleVersion</key>' "$SRC/Contents/Info.plist" | tail -n1 | sed -e 's/<[^>]*>//g' | xargs)
echo "Installer version: $INSTALLER_VERSION"

# =========================
# Version Check & Validation
# =========================
# Check if app is already installed and perform version comparison
if [ -d "$DEST" ]; then
    CURRENT_VERSION=$(grep -A1 '<key>CFBundleVersion</key>' "$DEST/Contents/Info.plist" | tail -n1 | sed -e 's/<[^>]*>//g' | xargs 2>/dev/null)
    if [ ! -z "$CURRENT_VERSION" ]; then
        echo "Current installed version: $CURRENT_VERSION"
        
        # Compare versions to determine installation action
        COMPARISON=$(version_compare "$CURRENT_VERSION" "$INSTALLER_VERSION")
        
        if [ "$COMPARISON" = "greater" ]; then
            # Prevent downgrade: current version is newer
            echo "ERROR: Current version ($CURRENT_VERSION) is newer than installer version ($INSTALLER_VERSION)"
            echo "Installation cancelled to prevent downgrade."
            
            # Show macOS alert dialog for downgrade attempt
            osascript -e "display alert \"Cannot Install Older Version\" message \"Installed version: $CURRENT_VERSION\" & return & \"Installer version: $INSTALLER_VERSION\" & return & return & \"The version you are trying to install is older than the currently installed version. Installation has been cancelled to prevent downgrade.\" as critical buttons {\"OK\"} default button \"OK\""
            
            exit 1
        elif [ "$COMPARISON" = "equal" ]; then
            # Skip installation: same version already installed
            echo "INFO: Same version ($CURRENT_VERSION) is already installed"
            echo "Installation cancelled - no update needed."
            
            # Show macOS info alert for same version
            osascript -e "display alert \"No Update Needed\" message \"Current version: $CURRENT_VERSION\" & return & \"Installer version: $INSTALLER_VERSION\" & return & return & \"This version is already installed on your system. No update is needed.\" as informational buttons {\"OK\"} default button \"OK\""
            
            exit 0
        fi
        # If COMPARISON = "lesser", proceed with installation (upgrade)
    fi
    
    # Remove existing installation before installing new version
    echo "Removing existing version at $DEST..."
    rm -rf "$DEST"
fi

# =========================
# Install New Version
# =========================
# Copy new app version from installer to Applications folder
echo "Copying new version to Applications..."
cp -R "$SRC" "$DEST"

# =========================
# Post-Installation Verification
# =========================
# Verify code signature integrity
echo "Verifying code signature..."
codesign --verify --verbose "$DEST" 2>/dev/null || echo "Warning: App signature verification failed"

# =========================
# Launch Application
# =========================
# Open the newly installed application
echo "Launching application..."
open "$DEST"

echo "Installation completed successfully!"
exit 0
