#!/bin/sh
# =============================================================================
# setup-apt-repo.sh — Configure the kioskos-agent apt repository
#
# Adds the Forgejo Debian package repository so the agent can be updated
# via apt-get.
#
# Usage:
#   setup-apt-repo.sh
#
# This script is idempotent — safe to run multiple times.
# =============================================================================

set -e

REPO_URL="https://code.jouleworks.net/api/packages/kioskOS/debian"
KEY_FILE="/etc/apt/keyrings/forgejo-kioskOS.asc"
SOURCES_FILE="/etc/apt/sources.list.d/forgejo.list"

echo "[kioskos-apt] Configuring kioskos-agent apt repository..."

if [ "$(id -u)" -ne 0 ]; then
    echo "ERROR: This script must be run as root." >&2
    exit 1
fi

# Install prerequisites
apt-get update -qq 2>/dev/null || true
apt-get install -y -qq curl ca-certificates 2>/dev/null || true

# Download the repository signing key
echo "[kioskos-apt] Downloading repository signing key..."
mkdir -p /etc/apt/keyrings
curl -fsSL "${REPO_URL}/repository.key" -o "${KEY_FILE}"

# Write the sources.list entry
echo "[kioskos-apt] Writing ${SOURCES_FILE}..."
echo "deb [arch=all signed-by=${KEY_FILE}] ${REPO_URL} bookworm main" > "${SOURCES_FILE}"
chmod 644 "${SOURCES_FILE}"

# Update apt cache
echo "[kioskos-apt] Updating apt cache..."
apt-get update -o Dir::Etc::sourcelist="${SOURCES_FILE}" -o Dir::Etc::sourceparts="-" -qq 2>/dev/null || {
    echo "[kioskos-apt] WARNING: apt update failed for kioskos repo — repo may not be available yet"
}

echo "[kioskos-apt] Apt repository configured successfully."
echo "[kioskos-apt] Install/update agent with: apt-get install kioskos-agent"
