#!/bin/bash
#
# Copyright (C) 2019-Present A-Team Digital Solutions
#

set -e

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

TOTAL_STEPS=6

echo "::PROGRESS::1::$TOTAL_STEPS"
echo "::STATUS::Downloading Update ..."
echo "URL: $URL"
if ! curl -L --fail \
    -o "$TMPDIR/update.7z" \
    "$URL"
then
    echo "::STATUS::Download Failed!"
    echo
    exit 1
fi

echo "::PROGRESS::2::$TOTAL_STEPS"
echo "::STATUS::Extracting Update ..."
if ! 7z x "$TMPDIR/update.7z" -o"$TMPDIR/extracted" -y >/dev/null 2>&1
then
    echo "::STATUS::Extraction Failed!"
    rm -rf "$TMPDIR"
    exit 1
fi

echo "::PROGRESS::3::$TOTAL_STEPS"
echo "::STATUS::Backing Up Current Installation ..."
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/extracted/scripts"
source update.sh

echo "::PROGRESS::6::$TOTAL_STEPS"
echo "::STATUS::Update Installed Successfully."
