#!/bin/bash
set -e

version=$(curl -sL https://api.github.com/repos/archimatetool/archi/tags | jq -r ".[0].name")
shortversion=$(echo "$version" |  cut -c 9-)
file="Archi-Linux64-${shortversion}.tgz"
url="https://github.com/archimatetool/archi.io/releases/download/${shortversion}/${file}"
download_path="/tmp/${file}"
optdir="/opt/Archi"

# Run only during configuration
if [ "$1" = "configure" ]; then
    # Delete target directory to ensure, upgrading to new version works correctly 
    if [ -d "$optdir" ]; then
        rm -rf "$optdir"
    fi
    # Ensure target directory exists
    mkdir -p "$optdir"

    # Download tarball if not already present
    [ -f "${download_path}" ] && rm -rf "${download_path}"

    echo "Download Archi ${shortversion}..."
    wget -q -O "${download_path}" "$url"

    # Extract tarball
    echo "Extracting Archi ${shortversion}..."
    tar -xzf "${download_path}" -C "$optdir" --strip-components=1

    # Removing Tarball
    rm -f "${download_path}"
fi
