#!/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-test-pkg"

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
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
echo "==> Updating package lists"
sudo apt-get update -qq

echo "==> Installing ${PACKAGE}"
sudo apt-get install -y "$PACKAGE"

echo "==> Done. Run '${PACKAGE}' to verify."
