#!/bin/bash

set -e

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

echo "::STATUS::Downloading Update ..."
echo "URL: $URL"
curl -L --fail \
    -o "$TMPDIR/update.7z" \
    "$URL"
echo
# Download Sanity Check
if [ $? -ne 0 ]; then
    echo "Download Failed!"
    echo
    exit 1
fi
sleep 5
echo "::STATUS::Extracting Update ..."
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
sleep 5
echo "::STATUS::Backing Up Current Installation ..."
#cp -a "$INSTALL_DIR" "$INSTALL_DIR.bak"
VERSION=$(python3 -c "
import importlib.util
spec = importlib.util.spec_from_file_location(
    'version',
    '$INSTALL_DIR/builder/version.py'
)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
print(mod.DISPLAY_VERSION)
")
PARENT_DIR=$(dirname "$INSTALL_DIR")
BACKUP="$INSTALL_DIR/A-Team-Android_ROM_Builder-BACKUP-${VERSION}.7z"
#rm -f "$BACKUP"
7z a -mx=9 "$BACKUP" "$INSTALL_DIR" >/dev/null
# save ENTIRE configs folder
#mkdir -p "$TMPDIR/preserve"
#cp -a \
#    "$INSTALL_DIR/configs" \
#    "$TMPDIR/preserve/" 2>/dev/null
#sleep 5
#echo "::STATUS::Installing Update ..."
#cp -a "$TMPDIR"/extracted/. "$INSTALL_DIR"/
# restore ENTIRE configs folder
#if [ -f "$TMPDIR/preserve/configs" ]; then
#    cp -a \
#        "$TMPDIR/preserve/configs" \
#        "$INSTALL_DIR"
#fi
#sleep 5
# Save SPECIFIC files in configs folder
#mkdir -p "$TMPDIR/preserve"
#cp -a \
#    "$INSTALL_DIR/configs/hosts.conf" \
#    "$TMPDIR/preserve/" 2>/dev/null
#sleep 5
echo "::STATUS::Installing Update ..."
cp -a "$TMPDIR"/extracted/. "$INSTALL_DIR"/
# Restore SPECIFIC files in configs folder
#if [ -f "$TMPDIR/preserve/hosts.conf" ]; then
#    cp -a \
#        "$TMPDIR/preserve/hosts.conf" \
#        "$INSTALL_DIR/configs/"
#fi
sleep 5
echo "::STATUS::Cleaning Up ..."
rm -rf "$TMPDIR"
sleep 5
exit 0
