#!/bin/bash

# Set the log file
LOGFILE="$PATCHDIR/patchlog.txt"

# Redirect output and error to the log file
exec > >(tee -a "$LOGFILE") 2>&1

echo "PATCHDIR is set to: $PATCHDIR"

# Exports
export LD_LIBRARY_PATH="/usr/lib:$GAMEDIR/lib:$GAMEDIR/tools/libs:$LD_LIBRARY_PATH"
export TOOLDIR="$PATCHDIR/tools"
export TMPDIR="$PATCHDIR/tmp"
export PATH=$PATH:$PATCHDIR/tools


# Permissions
chmod 666 /dev/uinput
chmod 777 "$TOOLDIR/gmKtool.py"
chmod 777 "$TOOLDIR/oggenc"

cd "$PATCHDIR"

process_game() {
    # Move assets from gamedata folder
    if [ -d "gamedata" ]; then
        mv gamedata/* .
        echo "Moved assets from gamedata to PATCHDIR."
        rm -rf gamedata
        echo "Removed gamedata directory."
    else
        echo "gamedata directory not found. Skipping asset move."
    fi

    # Define files to delete
    files_to_delete="Steamworks_x64.dll steam_appid.txt steam_api64.dll MAGO.exe"

    # Delete unnecessary files
    for file in $files_to_delete; do
        if [ -f "$file" ]; then
            rm "$file"
            echo "Deleted $file"
        else
            echo "$file not found"
        fi
    done

    # Check if the data.win file exists and its checksum
    if [ -f "data.win" ]; then
        checksum=$(md5sum "data.win" | awk '{print $1}')
        if [ "$checksum" = "7948b946e26ad8a95a7d2f86c800d1b9" ]; then
            # Apply the patch
            tools/xdelta3 -d -s "data.win" -f "./patch/mago.xdelta" "game.droid" && rm "data.win"
        fi
    fi

    # Compress audio
    if [ -f "compress.txt" ]; then
        echo "Compressing audio. The process will take 5-10 minutes."
        
        mkdir -p "$TMPDIR"

        # Run the compression tool
        echo "Running gmKtool.py with parameters..."
        ./tools/gmKtool.py -vvv -m 262144 -b 64 -d "$TMPDIR" "$PATCHDIR/game.droid"

        if [ $? -eq 0 ]; then
            echo "Compression completed successfully."
            mv "$TMPDIR/"* "$PATCHDIR"
            echo "Moved compressed files to $PATCHDIR."
            rm "$PATCHDIR/compress.txt"
            echo "Removed compress.txt from $PATCHDIR."
            rmdir "$TMPDIR"
            echo "Temporary directory $TMPDIR removed."
            echo "Audio compression applied successfully."
        else
            echo "Audio compression failed."
            echo "Cleaning up temporary directory $TMPDIR."
            rm -rf "$TMPDIR"
        fi
    else
        echo "compress.txt not found. Skipping audio compression."
    fi

    sleep 3

    # Check for .dat files and move to APK
    if [ -n "$(ls ./*.dat 2>/dev/null)" ]; then
        mkdir -p ./assets
        mv ./*.dat ./assets/
        echo "Moved .dat files to ./assets/"

        zip -r -0 ./game.apk ./assets/
        echo "Zipped contents to ./game.apk"

        rm -rf ./assets
        echo "Deleted assets directory"
    else
        echo "No .dat files found"
    fi
}

# Call the function
process_game
