#!/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/oggdec"
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" = "4a610f38d7d8d28e842099358b4061f7" ]; then
        $ESUDO ./tools/xdelta3 -d -s gamedata/data.win -f ./patch/sheeposteam.xdelta gamedata/game.droid && \
        rm gamedata/data.win
	echo "Steam version has been patched."
    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 "Checking for compress.txt"
sleep 3
mkdir -p "$TMPDIR"

# Run the compression tool
if [ -f "$GAMEDIR/compress.txt" ]; then
echo "Compressing audio..."
sleep 3
mkdir -p "$TMPDIR"

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
else
    echo "compress.txt not found, skipping audio compression"
fi

# Check for .dat files and move to APK
if [ -n "$(ls ./gamedata/*.dat 2>/dev/null)" ]; then
    mkdir -p ./assets
    mv ./gamedata/*.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


# Check if either "Sheepo.exe"exists
if [ -f "./gamedata/Sheepo.exe" ];  then    
    # Remove extra files from Steam or Itch.io builds
    rm -Rf "./gamedata/Sheepo.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

