#!/bin/bash
# Set GAMEDIR to the current directory and set logfile
GAMEDIR="$PWD"
LOGFILE="$GAMEDIR/patchlog.txt"

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

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

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

cd "$GAMEDIR"

# If "gamedata/data.win" exists and matches the checksum of the steam versions
if [ -f "./gamedata/data.win" ]; then
    checksum=$(md5sum "./gamedata/data.win" | awk '{print $1}')
    echo "Patching data.win"
    # Checksum for the Steam version
    if [ "$checksum" = "4d3ae781f133ae56ed8e9df8e5b40cee" ]; then
        $ESUDO ./tools/xdelta3 -d -s gamedata/data.win -f ./patch/topnep.xdelta gamedata/game.droid && \
        rm gamedata/data.win
    else
        echo "Error: MD5 checksum of data.win does not match any expected version."
	exit 1
    fi
else    
    echo "Error: Missing files in gamedata folder or game has been patched."
fi

# Compress audio
echo "Compressing audio..."
sleep 3
mkdir -p "$TMPDIR"

# Run the compression tool
PYTHON=$(which python3)
$PYTHON ./tools/gmKtool.py -vvv -m 1000 -r -b 64 -d "$TMPDIR" "$DATADIR/game.droid"

if [ $? -eq 0 ]; then
    echo "Compression completed successfully."
    mv "$TMPDIR/"* "$DATADIR"
    echo "Moved compressed files to $DATADIR."
    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

sleep 3

    # Find and compress all .ogg files in the /gamedata directory
    find "$GAMEDIR/gamedata" -type f -name "*.ogg" | while read -r file; do
    # Create a temporary file for the compressed version
    temp_file="${file%.ogg}_temp.ogg"

    # Decode the .ogg file and encode it with the specified bitrate
    "$TOOLDIR/oggdec" -o - "$file" | "$TOOLDIR/oggenc" -b 64 -o "$temp_file" -
    if [ $? -eq 0 ]; then
        # Replace the original file with the compressed version if successful
        mv "$temp_file" "$file"
        echo "Compressed: $file to 64 kbps"
    else
        echo "Failed to compress: $file" >&2
        rm -f "$temp_file" # Clean up the temp file in case of error
    fi
    done
    echo "All .ogg files have been processed."
    sleep 3    

# Pack Audio into apk and move game files to the right place
if [ -n "$(ls ./gamedata/*.dat 2>/dev/null)" ]; then
    # Move all audiogroup.dat from ./gamedata to ./assets
    mkdir -p ./assets
    mv ./gamedata/*.dat ./assets/ || exit 1
    mv ./gamedata/*.ogg ./assets/ || exit 1
    echo "Moved audiogroup.dat and .ogg files from ./gamedata to ./assets/"	

    # Zip the contents of ./game.apk including the new .dat and .ogg files
    zip -r -0 ./game.apk ./assets/ || exit 1
    echo "Zipped contents to ./game.apk"
    rm -Rf "$GAMEDIR/assets/" || exit 1
fi

# Check if either "TOP NEP.exe"exists
if [ -f "./gamedata/TOP NEP.exe" ]; then    
    # Remove extra files from Steam build
    rm -Rf "./gamedata/TOP NEP.exe" \
           "./gamedata/"*.dll \
	   "./gamedata/Place game files here" 
    echo "Extra game files removed, game patching complete!"
else    
    echo "No extra game files to remove, game has been patched!"
fi