#!/bin/bash

URL="$1"
INSTALL_DIR="$2"
TMPDIR=$(mktemp -d)

# Debugging
#echo "Archive: $ARCHIVE"
#echo "Install: $INSTALL_DIR"
#if [ ! -f "$ARCHIVE" ]; then
#    echo "ERROR: Archive Not Found!"
#    exit 1
#fi

echo "Downloading Update ..."
echo "URL: $URL"
echo 
#wget -O "$TMPDIR/update.7z" "$URL"
curl -L --fail -o "$TMPDIR/update.7z" "$URL"
# Download Sanity Check
if [ $? -ne 0 ]; then
    echo "Download Failed!"
    exit 1
fi
echo "Extracting Update ..."
7z x "$TMPDIR/update.7z" -o"$TMPDIR/extracted" -y
# Extract Sanity Check
if [ $? -ne 0 ]; then
    echo "Extraction failed!"
    rm -rf "$TMPDIR"
    exit 1
fi
echo "Waiting For ROM Builder To Close ..."
while pgrep -f gui.py >/dev/null
do
    sleep 1
done
echo "Backing Up Old Version ..."
cp -a "$INSTALL_DIR" "$INSTALL_DIR.bak"
echo "Installing ..."
cp -a "$TMPDIR"/extracted/update/. "$INSTALL_DIR"/
echo "Cleaning Up ..."
rm -rf "$TMPDIR"
echo "Restarting App ..."
cd "$INSTALL_DIR"
python3 gui.py &
exit 0
