#!/usr/bin/env bash
# Set up the Alan NULL APT repository. Installs no application packages.
set -euo pipefail

for command in curl gpg apt-get dpkg install awk mktemp; do
    command -v "$command" >/dev/null || { echo "Required command not found: $command" >&2; exit 1; }
done
if ((EUID != 0)); then
    command -v sudo >/dev/null || { echo 'Run as root or install sudo first.' >&2; exit 1; }
fi
case $(dpkg --print-architecture) in
    amd64|arm64) ;;
    *) echo 'This repository only provides amd64 and arm64 indexes.' >&2; exit 1 ;;
esac

expected='79D57295F80AC84CF56B72872700A3BD4392E7CC'
temporary=$(mktemp -d)
trap 'rm -rf "$temporary"' EXIT
mkdir -m 0700 "$temporary/gnupg"
curl --fail --show-error --location https://alan-null.github.io/apt/archive-key.asc --output "$temporary/archive-key.asc"
[[ $(head -n 1 "$temporary/archive-key.asc") == '-----BEGIN PGP PUBLIC KEY BLOCK-----' ]] || { echo 'Expected an ASCII-armored public key.' >&2; exit 1; }
gpg --homedir "$temporary/gnupg" --batch --with-colons --show-keys "$temporary/archive-key.asc" > "$temporary/key-info"
mapfile -t fingerprints < <(awk -F: '$1 == "pub" {primary=1; next} primary && $1 == "fpr" {print $10; primary=0}' "$temporary/key-info")
[[ ${#fingerprints[@]} == 1 && ${fingerprints[0]} == "$expected" ]] || { echo 'Signing key does not match the expected primary fingerprint; nothing installed.' >&2; exit 1; }
printf 'Verified signing key: %s\n' "$expected"

cat > "$temporary/alan-null.sources" <<'SOURCES'
Types: deb
URIs: https://alan-null.github.io/apt/
Suites: stable
Components: main
Signed-By: /etc/apt/keyrings/alan-null-archive.asc
SOURCES

privileged=()
if ((EUID != 0)); then privileged=(sudo); fi
"${privileged[@]}" install -d -m 0755 /etc/apt/keyrings /etc/apt/sources.list.d
"${privileged[@]}" install -m 0644 "$temporary/archive-key.asc" /etc/apt/keyrings/alan-null-archive.asc
"${privileged[@]}" install -m 0644 "$temporary/alan-null.sources" /etc/apt/sources.list.d/alan-null.sources
"${privileged[@]}" apt-get update
printf '\nRepository ready. List available packages with:\n  apt list '\''?origin(Alan NULL)'\''\n'
