#!/bin/bash
#
# Adds the MergeTB apt repository to a Debian/Ubuntu host.
#   curl -fsSL https://pkg.mergetb.net/addrepo | bash
#
# Installs the repo's public key into /etc/apt/keyrings (scoped, not global)
# and writes a sources entry that trusts that key for this repo only via
# signed-by. Replaces the deprecated apt-key add path (apt-key was removed in
# Debian 13 / last shipped in Debian 12 + Ubuntu 24.04).

set -e

KEY_URL="https://pkg.mergetb.net/gpg"
REPO_URL="https://pkg.mergetb.net/debian"
SUITE="mergetb"
COMPONENT="main"
KEYRING="/etc/apt/keyrings/mergetb.gpg"
LIST="/etc/apt/sources.list.d/mergetb.list"

# Need root, or sudo, to write under /etc/apt.
SUDO=
if [[ $(id -u) -ne 0 ]]; then
    if command -v sudo >/dev/null 2>&1; then
        SUDO=$(command -v sudo)
    else
        echo "Run as root or install sudo." >&2
        exit 1
    fi
fi

# gpg is needed to dearmor the ASCII-armored key into apt's binary format.
if ! command -v gpg >/dev/null 2>&1; then
    $SUDO apt-get update
    $SUDO apt-get install -y gnupg
fi
# curl to fetch the key.
if ! command -v curl >/dev/null 2>&1; then
    $SUDO apt-get update
    $SUDO apt-get install -y curl ca-certificates
fi

# Install the signing key, scoped to this repo via signed-by.
# /etc/apt/keyrings is apt's recommended location for admin-added keys (>= APT 2.4).
$SUDO install -d -m 0755 /etc/apt/keyrings
curl -fsSL "$KEY_URL" | $SUDO gpg --dearmor -o "$KEYRING"
$SUDO chmod 0644 "$KEYRING"

# Write the sources entry pinned to that one key.
echo "deb [signed-by=${KEYRING}] ${REPO_URL} ${SUITE} ${COMPONENT}" \
    | $SUDO tee "$LIST" >/dev/null

$SUDO apt-get update
echo "MergeTB repository added (suite: ${SUITE})."
