#!/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"

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" = "8584c4d3227e3219c9ac6db2ca3ff162" ]; then
        $ESUDO ./tools/xdelta3 -d -s gamedata/data.win -f ./patch/hatchwell.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

# Check if either "Hatchwell.exe"exists
if [ -f "./gamedata/Hatchwell.exe" ]; then    
    # Remove extra files from Steam or Itch.io builds
    rm -Rf "./gamedata/Hatchwell.exe" \
           "./gamedata/"*.dll \
	   "./gamedata/Place game files here" 
    echo "Extra game files removed and patching is complete!"
else    
    echo "No extra game files to remove"
fi

