#!/bin/bash
set -e

REPO_HOST="${VCF_REPO_HOST:-https://packages.v8-rnd.com/apt}"
KEYRING="/usr/share/keyrings/vcf-rnd-archive-keyring.gpg"
SOURCES_FILE="/etc/apt/sources.list.d/vcf-rnd.list"
PACKAGE="vcf-licence"

echo "==> Installing $PACKAGE from VCF R&D repository"

# Ensure curl and gpg exist
if ! command -v curl >/dev/null 2>&1; then
    echo "==> Installing curl..."
    sudo apt-get update -qq
    sudo apt-get install -y curl
fi

if ! command -v gpg >/dev/null 2>&1; then
    echo "==> Installing gnupg..."
    sudo apt-get install -y gnupg
fi

# Import the GPG key (--yes avoids an interactive overwrite prompt on re-runs)
echo "==> Importing repository signing key"
curl -fsSL "${REPO_HOST}/archive-key.asc" | sudo gpg --yes --dearmor -o "$KEYRING"

# Add the repo source
echo "==> Adding repository source"
echo "deb [signed-by=${KEYRING}] ${REPO_HOST} stable main" | sudo tee "$SOURCES_FILE" > /dev/null

# Update and install — apt resolves libwebkit2gtk-4.1-0 and libgtk-3-0 automatically
echo "==> Updating package lists"
sudo apt-get update -qq

echo "==> Installing ${PACKAGE} (this pulls in WebKitGTK + GTK3 if not already present)"
sudo apt-get install -y "$PACKAGE"

echo "==> Done. Launch '${PACKAGE}' from your applications menu, or run '${PACKAGE}' in a terminal."