#!/bin/bash

set -e

URL="$1"
export INSTALL_DIR="$2"
export 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"
7z a -mx=9 "$BACKUP" "$INSTALL_DIR" >/dev/null

cd $TMPDIR/scripts
bash update.sh

