#!/bin/bash
# Convenience script to update the F-Droid repository with the correct environment.

export LD_LIBRARY_PATH=/usr/lib/jvm/java-21-openjdk-amd64/lib
export PATH="/home/jombo/rekindle/FDROIDREPO/local_tools/usr/lib/jvm/java-21-openjdk-amd64/bin:$PATH"

echo "Updating F-Droid repository..."

# Sync the latest APK to the repo folder
if [ -f app-release.apk ]; then
    echo "Found new app-release.apk, syncing to repo..."
    cp app-release.apk repo/rekindleAndroid-0_9.apk
    # Also update the root file to keep it consistent
    cp app-release.apk rekindleAndroid-0_9.apk
elif [ -f rekindleAndroid-0_9.apk ]; then
    cp rekindleAndroid-0_9.apk repo/
fi

./venv/bin/fdroid update --verbose

# Force lastupdated to today in XML
TODAY=$(date +%Y-%m-%d)
echo "Forcing lastupdated to $TODAY in index.xml"
sed -i "s/<lastupdated>[0-9-]*<\/lastupdated>/<lastupdated>$TODAY<\/lastupdated>/g" repo/index.xml
sed -i "s/<added>[0-9-]*<\/added>/<added>$TODAY<\/added>/g" repo/index.xml

# Re-sign the index. F-Droid signindex will handle regenerating the signed JARs and entry.json
echo "Re-signing index..."
./venv/bin/fdroid signindex --verbose

if [ $? -eq 0 ]; then
    echo "Update successful. Rebuilding Docker image..."
    docker build -t fdroid-repo .
    echo "Restarting container..."
    docker stop rekindle-fdroid
    docker rm rekindle-fdroid
    docker run -d --name rekindle-fdroid -p 8081:80 fdroid-repo
    echo "Done!"
else
    echo "Update failed. Check logs."
    exit 1
fi
