#!/bin/bash
set -e

version=$(curl -sL https://api.github.com/repos/ventoy/Ventoy/releases/latest | jq -r ".tag_name")
shortversion=$(echo $version | cut -c 2-)
file="ventoy-${shortversion}-linux.tar.gz"
url="https://github.com/ventoy/Ventoy/releases/download/${version}/${file}"
download_path="/tmp/${file}"
optdir="/opt/Ventoy"

# 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 Ventoy ${shortversion}..."
    wget -q -O "${download_path}" "$url"

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

    # Remove unused architectures 
    rm "$optdir"/VentoyGUI.{aarch64,i386,mips64el}

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