#!/bin/bash
# EQ Package Repository — client bootstrap (R2 / token edition)
#
# Usage:
#   curl -fsSL https://deb.eq.systems/setup.sh | sudo bash -s -- <TOKEN>
#   curl -fsSL https://deb.eq.systems/setup.sh | sudo bash -s -- <TOKEN> https://deb.eq.systems
#
# Installs the GPG signing key, adds the APT source, and writes the read token to
# /etc/apt/auth.conf.d so `apt update` authenticates to the token-gated repo.
# Idempotent.
set -euo pipefail

TOKEN="${1:-}"
REPO_URL="${2:-https://deb.eq.systems}"
REPO_URL="${REPO_URL%/}"
HOST="${REPO_URL#https://}"; HOST="${HOST#http://}"

KEYRING="/usr/share/keyrings/eq-systems.gpg"
SOURCES_LIST="/etc/apt/sources.list.d/eq-systems.list"
AUTH_CONF="/etc/apt/auth.conf.d/eq-packages.conf"

[ -n "$TOKEN" ] || { echo "ERROR: pass the package token as the first argument" >&2; exit 1; }

echo "Setting up EQ package repository: $REPO_URL"

echo "  Installing GPG signing key…"
curl -fsSL "$REPO_URL/repo-signing.gpg" | gpg --dearmor --yes -o "$KEYRING"
chmod 644 "$KEYRING"

echo "  Writing APT auth token…"
install -d -m 700 /etc/apt/auth.conf.d
printf 'machine %s login packages password %s\n' "$HOST" "$TOKEN" > "$AUTH_CONF"
chmod 600 "$AUTH_CONF"

echo "  Adding APT source…"
cat > "$SOURCES_LIST" <<EOF
# EQ Systems package repository
# Managed by: curl -fsSL $REPO_URL/setup.sh | sudo bash -s -- <TOKEN>
deb [signed-by=$KEYRING] $REPO_URL/ stable main
EOF

echo "  Running apt update…"
apt-get update -o Dir::Etc::sourcelist="$SOURCES_LIST" \
               -o Dir::Etc::sourceparts="-" -o APT::Get::List-Cleanup="0"

echo ""
echo "EQ package repository configured."
echo "  Install:  sudo apt install eq-coherence    # or eq-managed on a Nebula gateway"
