#!/bin/bash

set -e

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