#!/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
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
echo "::STATUS::Backing Up Current Installation ..."
cp -a "$INSTALL_DIR" "$INSTALL_DIR.bak"
echo "::STATUS::Installing Update ..."
cp -a "$TMPDIR"/extracted/. "$INSTALL_DIR"/
echo "::STATUS::Cleaning Up ..."
rm -rf "$TMPDIR"
echo "::STATUS::Update Complete."
exit 0
