#!/bin/bash
set -Eeuo pipefail
umask 022
export LC_ALL=C PATH=/usr/sbin:/usr/bin:/sbin:/bin
unset APT_CONFIG GNUPGHOME GPG_AGENT_INFO

origin=https://mirrors.scalarx.net/stackx-debian
fingerprint=AF97ED98AACE4CE129A03B6E2C9736B593BABF7F
keyring_sha256=ef99512024cd556d69624c7da524882cc8f12cd3de04034f43ad876b38b76327
keyring=/usr/share/keyrings/stackx-debian-archive.gpg
source_list=/etc/apt/sources.list.d/stackx-debian.list
apt_helper=/usr/lib/apt/apt-helper

die() { printf 'Erreur : %s\n' "$*" >&2; exit 1; }

[[ $# -eq 0 ]] || die 'Usage : bash add-stackx-debian-repo.sh'
[[ $(id -u) -eq 0 ]] || die 'Lancer ce script avec les droits root.'
for name in apt-get cmp dpkg flock gpgv mktemp sha256sum; do
    command -v "$name" >/dev/null || die "Commande requise : $name"
done
[[ -x "$apt_helper" && -x /usr/lib/apt/methods/https ]] ||
    die "La méthode HTTPS d’APT est requise (apt-transport-https sur Stretch)."
[[ -s /etc/ssl/certs/ca-certificates.crt ]] || die 'Le paquet ca-certificates est requis.'
[[ $(dpkg --print-architecture) = amd64 ]] || die "Seule l’architecture amd64 est prise en charge."

os_release=/etc/os-release
if [[ -L "$os_release" ]]; then
    [[ $(readlink -f -- "$os_release") = /usr/lib/os-release ]] || die 'Lien os-release inattendu.'
fi
[[ -f "$os_release" ]] || die 'Fichier os-release introuvable.'
os_field() { awk -F= -v field="$1" '$1 == field {gsub(/^"|"$/,"",$2); print $2}' "$os_release"; }
[[ $(os_field ID) = debian ]] || die 'Ce dépôt est réservé à Debian.'
case $(os_field VERSION_ID) in
    9) distro=stretch ;;
    10) distro=buster ;;
    11) distro=bullseye ;;
    *) die 'Seules Debian 9 Stretch, 10 Buster et 11 Bullseye sont prises en charge.' ;;
esac
codename=$(os_field VERSION_CODENAME)
[[ -z "$codename" || "$codename" = "$distro" ]] || die 'Identification Debian incohérente.'
suite=$distro-stackx-security

for directory in /run /usr/share/keyrings /etc/apt/sources.list.d; do
    [[ -d "$directory" && ! -L "$directory" ]] || die "Répertoire système inattendu : $directory"
done
lock=/run/stackx-debian-repo.lock
[[ ! -L "$lock" && ( ! -e "$lock" || -f "$lock" ) ]] || die "Verrou non régulier : $lock"
exec 9>>"$lock"
flock -n 9 || die 'Une autre installation du dépôt StackX Debian est en cours.'
for path in "$keyring" "$source_list"; do
    [[ ! -L "$path" && ( ! -e "$path" || -f "$path" ) ]] || die "Fichier existant non régulier : $path"
done

work=$(mktemp -d /tmp/stackx-debian-repo.XXXXXXXX)
pending=()
created_key=0
cleanup() {
    local result=$?
    if (( result != 0 && created_key == 1 )) &&
        [[ -f "$keyring" && ! -L "$keyring" ]] && cmp -s -- "$work/key.gpg" "$keyring"; then
        rm -f -- "$keyring"
    fi
    if (( ${#pending[@]} )); then
        rm -f -- "${pending[@]}"
    fi
    rm -rf -- "$work"
}
trap cleanup EXIT
chmod 0755 "$work"
mkdir -m 0700 "$work/gnupg"
mkdir "$work/empty" "$work/lists"

printf 'deb [arch=amd64 signed-by=%s] %s %s main\n' "$keyring" "$origin" "$suite" > "$work/source.list"
if [[ -e "$source_list" ]] && ! cmp -s -- "$work/source.list" "$source_list"; then
    die "Configuration personnalisée conservée : $source_list"
fi
for file in /etc/apt/sources.list /etc/apt/sources.list.d/*.list /etc/apt/sources.list.d/*.sources; do
    [[ -f "$file" && "$file" != "$source_list" ]] || continue
    if awk '/^[[:space:]]*#/ {next} /https?:\/\/mirrors\.scalarx\.net\/stackx-debian([[:space:]\/]|$)/ {found=1} END {exit !found}' "$file"; then
        die "Le dépôt StackX Debian figure déjà dans $file."
    fi
done

# Isolate APT's lists, configuration and hooks during preflight.
cat > "$work/apt.conf" <<EOF
Dir::Etc::parts "$work/empty";
Dir::Etc::main "$work/empty/apt.conf";
Dir::Etc::sourceparts "$work/empty";
Dir::State::lists "$work/lists";
Dir::Cache::pkgcache "";
Dir::Cache::srcpkgcache "";
Acquire::Languages "none";
Acquire::https::Verify-Peer "true";
Acquire::https::Verify-Host "true";
Acquire::AllowInsecureRepositories "false";
Acquire::AllowDowngradeToInsecureRepositories "false";
APT::Get::AllowUnauthenticated "false";
EOF
invoke_apt() { APT_CONFIG="$work/apt.conf" "$@"; }
download() {
    local url=$1 destination=$2 limit=$3
    if ! invoke_apt "$apt_helper" download-file "$url" "$destination" > "$work/download.log" 2>&1; then
        cat "$work/download.log" >&2
        die "Téléchargement HTTPS impossible : $url"
    fi
    [[ -f "$destination" && -s "$destination" && $(wc -c < "$destination") -le "$limit" ]] ||
        die "Taille inattendue du fichier reçu : $url"
}

if [[ -f "$keyring" ]]; then
    cp -- "$keyring" "$work/key.gpg"
else
    download "$origin/stackx-debian-archive.gpg" "$work/key.gpg" 65536
fi
# Pin the whole public keyring so additional keys cannot share the APT trust.
printf '%s  %s\n' "$keyring_sha256" "$work/key.gpg" | sha256sum -c --status - ||
    die 'Le trousseau reçu diffère du trousseau public historique StackX.'
chmod 0644 "$work/key.gpg"
download "$origin/dists/$suite/InRelease" "$work/InRelease" 1048576
gpgv --homedir "$work/gnupg" --keyring "$work/key.gpg" --status-fd 1 \
    --output "$work/Release" "$work/InRelease" > "$work/signature.log" 2>&1 ||
    die 'Signature du catalogue invalide.'
grep -Fq "VALIDSIG $fingerprint " "$work/signature.log" || die 'Signataire du catalogue inattendu.'
for line in 'Origin: StackX' "Suite: $suite" "Codename: $suite" 'Architectures: amd64' 'Components: main'; do
    grep -Fxq "$line" "$work/Release" || die "Champ du catalogue absent ou inattendu : $line"
done
priority_metadata=$(awk 'tolower($0) ~ /^notautomatic:/ {print}' "$work/Release")
case $priority_metadata in
    ''|'NotAutomatic: yes') ;;
    *) die 'Champ NotAutomatic du catalogue inattendu.' ;;
esac

printf 'deb [arch=amd64 signed-by=%s] %s %s main\n' "$work/key.gpg" "$origin" "$suite" > "$work/preflight.list"
if ! invoke_apt apt-get -o "Dir::Etc::sourcelist=$work/preflight.list" \
    -o Acquire::AllowInsecureRepositories=false -o Acquire::AllowDowngradeToInsecureRepositories=false \
    -o APT::Get::AllowUnauthenticated=false update > "$work/apt-update.log" 2>&1; then
    cat "$work/apt-update.log" >&2
    die "APT refuse le catalogue $suite."
fi
prefix="mirrors.scalarx.net_stackx-debian_dists_${suite}"
if ! cmp -s -- "$work/InRelease" "$work/lists/${prefix}_InRelease" ||
    [[ -z $(find "$work/lists" -maxdepth 1 -type f -name "${prefix}_main_binary-amd64_Packages*" -size +0c -print -quit) ]]; then
    cat "$work/apt-update.log" >&2
    die "APT n’a pas enregistré le catalogue signé attendu et son index amd64."
fi

publish_new() {
    local input=$1 path=$2 staged
    staged=$(mktemp "${path}.XXXXXXXX") || return 1
    pending+=("$staged")
    install -m 0644 -- "$input" "$staged" && ln -T -- "$staged" "$path"
}
if [[ -e "$keyring" || -L "$keyring" ]]; then
    if [[ ! -f "$keyring" || -L "$keyring" ]] || ! cmp -s -- "$work/key.gpg" "$keyring"; then
        die "Le fichier $keyring a changé pendant la vérification."
    fi
else
    publish_new "$work/key.gpg" "$keyring" || die "Impossible de créer $keyring sans écraser un fichier existant."
    created_key=1
fi
if [[ -e "$source_list" || -L "$source_list" ]]; then
    if [[ ! -f "$source_list" || -L "$source_list" ]] || ! cmp -s -- "$work/source.list" "$source_list"; then
        die "Le fichier $source_list a changé pendant la vérification."
    fi
else
    publish_new "$work/source.list" "$source_list" || die "Impossible de créer $source_list sans écraser un fichier existant."
fi

printf 'Dépôt StackX Debian configuré pour %s amd64.\n' "$distro"
printf 'Lancer apt-get update pour actualiser les listes système.\n'
if [[ -z $priority_metadata && $distro != stretch ]]; then
    printf '%s\n' 'Si APT signale un changement de priorité par défaut pour ce dépôt, accepter ce changement une fois :' \
        'apt-get -o Acquire::AllowReleaseInfoChange::DefaultPin=true update'
fi
