#!/bin/bash
# StackX-Apache-Version: 2.4.59-1~deb10u10+sx7
# Ajoute uniquement le dépôt Apache StackX buster amd64 après vérifications.
# N'installe aucun paquet Apache, ne redémarre aucun service.
set -euo pipefail
umask 077
export LC_ALL=C
unset APT_CONFIG GNUPGHOME GPG_AGENT_INFO

DIST='buster'
DEBIAN_MAJOR='10'
APACHE_VERSION='2.4.59-1~deb10u10+sx7'
PACKAGES_SHA256='6724b03fe57e4ea9f51a0b38e90218d8c7caa81811ebf5e52676daf60f8b3078'
PACKAGE_COUNT='15'
PACKAGE_NAMES='apache2 apache2-bin apache2-bin-dbgsym apache2-data apache2-dev apache2-doc apache2-ssl-dev apache2-suexec-custom apache2-suexec-custom-dbgsym apache2-suexec-pristine apache2-suexec-pristine-dbgsym apache2-utils apache2-utils-dbgsym libapache2-mod-md libapache2-mod-proxy-uwsgi'
EXPECTED_FPR='AF97ED98AACE4CE129A03B6E2C9736B593BABF7F'
ORIGIN="https://mirrors.scalarx.net/stackx-apache/$DIST"
KEY_URL="$ORIGIN/stackx-apache-repository.asc"
INRELEASE_URL="$ORIGIN/InRelease"
PACKAGES_URL="$ORIGIN/Packages"
KEYRING="/usr/share/keyrings/stackx-apache-$DIST.gpg"
LIST="/etc/apt/sources.list.d/stackx-apache-$DIST.list"
APT_HELPER=/usr/lib/apt/apt-helper
LIST_PREFIX="mirrors.scalarx.net_stackx-apache_${DIST}_"
created_key=0
created_list=0

die() { echo "erreur : $*" >&2; exit 1; }
fail() {
    echo "erreur : $*" >&2
    if [[ "$created_list" -eq 1 && -f "$LIST" && ! -L "$LIST" ]] &&
       cmp -s -- "$work/source.list" "$LIST"; then
        rm -f -- "$LIST"
    fi
    if [[ "$created_key" -eq 1 && -f "$KEYRING" && ! -L "$KEYRING" ]] &&
       cmp -s -- "$work/keyring.gpg" "$KEYRING"; then
        rm -f -- "$KEYRING"
    fi
    echo "Aucun paquet Apache installé, aucun service redémarré." >&2
    exit 1
}

[[ $# -eq 0 ]] || die "usage : add-stackx-apache-repo.sh (sans argument)"
[[ "$(id -u)" -eq 0 ]] || die "root est requis"
[[ "$APACHE_VERSION" =~ ^2\.4\.[0-9]+[A-Za-z0-9.+~_-]*\+sx[0-9]+$ &&
   "$PACKAGES_SHA256" =~ ^[0-9a-f]{64}$ &&
   "$PACKAGE_COUNT" =~ ^[0-9]+$ ]] || die "gabarit non finalisé : version, index ou nombre de paquets absent"

for cmd in dpkg gpg gpgv awk grep cmp sha256sum wc mktemp chmod cp ln rm find head tr mkdir readlink dirname; do
    command -v "$cmd" >/dev/null 2>&1 || die "commande absente : $cmd"
done
[[ -x "$APT_HELPER" ]] || die "apt-helper absent"
[[ -x /usr/lib/apt/methods/https ]] || die "méthode APT HTTPS absente"
[[ -f /etc/ssl/certs/ca-certificates.crt &&
   ! -L /etc/ssl/certs/ca-certificates.crt &&
   -s /etc/ssl/certs/ca-certificates.crt ]] || die "certificats TLS absents"

if [[ -L /etc/os-release ]]; then
    [[ "$(readlink -f /etc/os-release)" == /usr/lib/os-release ]] ||
        die "lien /etc/os-release inattendu"
    os_file=/usr/lib/os-release
else
    os_file=/etc/os-release
fi
[[ -f "$os_file" && ! -L "$os_file" ]] || die "os-release illisible"
os_id= os_version= os_codename=
while IFS= read -r line || [[ -n "$line" ]]; do
    case "$line" in
        ID=*|VERSION_ID=*|VERSION_CODENAME=*)
            key=${line%%=*}
            value=${line#*=}
            value=${value#\"}
            value=${value%\"}
            case "$key" in
                ID) os_id=$value ;;
                VERSION_ID) os_version=$value ;;
                VERSION_CODENAME) os_codename=$value ;;
            esac ;;
    esac
done < "$os_file"
[[ "$os_id" == debian && "$os_version" == "$DEBIAN_MAJOR" &&
   "$(dpkg --print-architecture)" == amd64 ]] ||
    die "seule Debian $DEBIAN_MAJOR $DIST amd64 est acceptée"
[[ -z "$os_codename" || "$os_codename" == "$DIST" ]] ||
    die "nom de distribution incompatible"
[[ ! -L /etc/debian_version ]] || die "lien /etc/debian_version refusé"
if [[ -f /etc/debian_version ]]; then
    debian_version=$(head -n 1 /etc/debian_version)
    [[ "$debian_version" == "$DEBIAN_MAJOR"* ]] ||
        die "version Debian incompatible"
fi

[[ -d /usr/share/keyrings && ! -L /usr/share/keyrings &&
   -d /etc/apt/sources.list.d && ! -L /etc/apt/sources.list.d ]] ||
    die "répertoires APT inattendus"
[[ ! -L "$KEYRING" && ! -L "$LIST" ]] || die "lien symbolique APT refusé"
[[ ! -e "$KEYRING" || -f "$KEYRING" ]] || die "trousseau APT non régulier"
[[ ! -e "$LIST" || -f "$LIST" ]] || die "liste APT non régulière"
command -v apt-get >/dev/null 2>&1 || die "apt-get absent"

work=$(mktemp -d "/tmp/stackx-apache-$DIST-repo.XXXXXX")
chmod 700 "$work"
trap 'rm -rf -- "$work"' EXIT
mkdir -m 700 "$work/gnupg"

# Tous les téléchargements et contrôles ci-dessous précèdent l'écriture APT.
download() {
    local url=$1 target=$2
    "$APT_HELPER" -o Acquire::https::Verify-Peer=true \
                  -o Acquire::https::Verify-Host=true \
                  download-file "$url" "$target" >"$work/download.log" 2>&1 ||
        die "téléchargement HTTPS ou contrôle TLS refusé : $url"
    [[ -f "$target" && ! -L "$target" && -s "$target" ]] ||
        die "fichier téléchargé invalide : $url"
}
download "$KEY_URL" "$work/key.asc"
key_bytes=$(wc -c < "$work/key.asc")
[[ "$key_bytes" -ge 32 && "$key_bytes" -le 65536 ]] || die "taille de clé refusée"
grep -Fq -- '-----BEGIN PGP PUBLIC KEY BLOCK-----' "$work/key.asc" ||
    die "clé non armurée"
gpg --no-options --batch --no-tty --no-autostart \
    --homedir "$work/gnupg" --list-packets "$work/key.asc" \
    >"$work/key.packets" 2>"$work/key.packets.err" ||
    die "paquets OpenPGP invalides"
[[ "$(grep -Fc ':public key packet:' "$work/key.packets" || true)" -eq 1 ]] ||
    die "une seule clé primaire publique est permise"
if grep -Fq -e ':secret key packet:' -e ':secret sub key packet:' "$work/key.packets"; then
    die "matériel de clé privée refusé"
fi
gpg --no-options --batch --no-tty --no-autostart \
    --homedir "$work/gnupg" --show-keys --with-colons --fingerprint "$work/key.asc" \
    >"$work/key.list" 2>"$work/key.list.err" ||
    die "clé publique illisible"
[[ "$(grep -c '^pub:' "$work/key.list" || true)" -eq 1 ]] ||
    die "nombre de clés primaires inattendu"
primary_fpr=$(awk -F: '$1 == "fpr" { print $10; exit }' "$work/key.list")
[[ "$primary_fpr" == "$EXPECTED_FPR" ]] ||
    die "empreinte de clé APT différente de la clé historique StackX"
gpg --no-options --batch --no-tty --no-autostart \
    --homedir "$work/gnupg" --dearmor \
    --output "$work/keyring.gpg" "$work/key.asc" \
    >"$work/dearmor.log" 2>&1 || die "clé impossible à convertir"

download "$INRELEASE_URL" "$work/InRelease.fresh"
[[ "$(wc -c < "$work/InRelease.fresh")" -le 1048576 ]] ||
    die "InRelease trop volumineux"
gpgv --homedir "$work/gnupg" --keyring "$work/keyring.gpg" \
     --output "$work/Release" "$work/InRelease.fresh" \
     >"$work/gpgv.log" 2>&1 ||
    die "InRelease non signé par la clé StackX épinglée"
for field in "Origin: StackX" "Label: StackX Apache $DIST" \
             "Suite: $DIST" "Codename: $DIST" "Architectures: amd64"; do
    [[ "$(grep -Fxc -- "$field" "$work/Release" || true)" -eq 1 ]] ||
        die "champ Release absent ou répété : $field"
done
release_package_row=$(awk '
    $0 == "SHA256:" { inside=1; next }
    inside && /^ / { if ($3 == "Packages") { print $1 " " $2; found++ }; next }
    inside { inside=0 }
    END { if (found != 1) exit 1 }
' "$work/Release") || die "index Packages absent ou répété dans Release"
read -r release_hash release_size <<<"$release_package_row"
[[ "$release_hash" == "$PACKAGES_SHA256" &&
   "$release_size" =~ ^[0-9]+$ ]] ||
    die "empreinte Packages différente de la livraison qualifiée"

download "$PACKAGES_URL" "$work/Packages.fresh"
[[ "$(wc -c < "$work/Packages.fresh")" -le 8388608 ]] ||
    die "Packages trop volumineux"
[[ "$(sha256sum "$work/Packages.fresh" | awk '{print $1}')" == "$PACKAGES_SHA256" &&
   "$(wc -c < "$work/Packages.fresh")" -eq "$release_size" ]] ||
    die "Packages ne correspond pas à Release signé et à l'empreinte épinglée"
awk -v expected="$PACKAGE_COUNT" -v version="$APACHE_VERSION" \
    -v allowed="$PACKAGE_NAMES" '
    BEGIN {
        n=split(allowed, names, " ")
        for (i=1; i<=n; i++) permitted[names[i]]=1
        if (n != expected) bad=1
    }
    function finish() {
        if (pkg == "") return
        count++
        if (!permitted[pkg] || seen[pkg]++ || ver != version ||
            (arch != "amd64" && arch != "all") ||
            file !~ /^pool\/[A-Za-z0-9.+_~%-]+\.deb$/ ||
            length(hash) != 64 || hash !~ /^[0-9a-f]+$/ ||
            size !~ /^[0-9]+$/) bad=1
        pkg=ver=arch=file=hash=size=""
    }
    /^Package: / { pkg=substr($0,10) }
    /^Version: / { ver=substr($0,10) }
    /^Architecture: / { arch=substr($0,15) }
    /^Filename: / { file=substr($0,11) }
    /^SHA256: / { hash=substr($0,9) }
    /^Size: / { size=substr($0,7) }
    /^$/ { finish() }
    END { finish(); if (bad || count != expected) exit 1 }
' "$work/Packages.fresh" || die "liste des paquets Apache inattendue"

{
    echo "# Dépôt Apache StackX $DIST amd64, version $APACHE_VERSION."
    printf 'deb [arch=amd64 signed-by=%s] %s ./\n' "$KEYRING" "$ORIGIN"
} >"$work/source.list"
if [[ -f "$KEYRING" ]] && ! cmp -s -- "$work/keyring.gpg" "$KEYRING"; then
    die "un autre trousseau occupe déjà $KEYRING"
fi
if [[ -f "$LIST" ]] && ! cmp -s -- "$work/source.list" "$LIST"; then
    die "une autre source APT occupe déjà $LIST"
fi
source_paths=(/etc/apt/sources.list.d)
[[ -f /etc/apt/sources.list ]] && source_paths+=(/etc/apt/sources.list)
if grep -r -n -F -- "$ORIGIN" "${source_paths[@]}" 2>/dev/null |
   grep -v -F -- "$LIST:" | grep -q .; then
    die "canal déjà déclaré dans une autre source APT"
fi

install_once() {
    local source=$1 dest=$2 temp
    [[ ! -L "$dest" ]] || return 1
    if [[ -f "$dest" ]]; then
        cmp -s -- "$source" "$dest"
        return
    fi
    temp=$(mktemp "$(dirname "$dest")/.stackx-apache.XXXXXX")
    cp -- "$source" "$temp" || { rm -f -- "$temp"; return 1; }
    chmod 644 "$temp"
    ln -- "$temp" "$dest" || { rm -f -- "$temp"; return 1; }
    rm -f -- "$temp"
}
[[ -e "$KEYRING" ]] || created_key=1
[[ -e "$LIST" ]] || created_list=1
install_once "$work/keyring.gpg" "$KEYRING" || fail "écriture du trousseau impossible"
install_once "$work/source.list" "$LIST" || fail "écriture de la source APT impossible"

apt-get update \
    -o "Dir::Etc::sourcelist=sources.list.d/stackx-apache-$DIST.list" \
    -o Dir::Etc::sourceparts=- -o APT::Get::List-Cleanup=0 \
    -o Acquire::AllowInsecureRepositories=false \
    -o Acquire::AllowDowngradeToInsecureRepositories=false \
    -o APT::Get::AllowUnauthenticated=false \
    -o Acquire::https::Verify-Peer=true \
    -o Acquire::https::Verify-Host=true ||
    fail "rafraîchissement du seul canal StackX impossible"
cached=
for candidate in "/var/lib/apt/lists/${LIST_PREFIX}InRelease" \
                 "/var/lib/apt/lists/${LIST_PREFIX}._InRelease"; do
    if [[ -f "$candidate" && ! -L "$candidate" && -s "$candidate" ]]; then
        [[ -z "$cached" ]] || fail "plusieurs InRelease en cache"
        cached=$candidate
    fi
done
[[ -n "$cached" ]] || fail "InRelease signé absent du cache APT"
cmp -s -- "$work/InRelease.fresh" "$cached" ||
    fail "InRelease en cache différent du document fraîchement vérifié"
find /var/lib/apt/lists -maxdepth 1 -type f \
    -name "${LIST_PREFIX}*Packages*" >"$work/pkg-cache.paths"
cached_count=0
while IFS= read -r candidate; do
    [[ -f "$candidate" && ! -L "$candidate" ]] ||
        fail "index Packages en cache invalide"
    "$APT_HELPER" cat-file "$candidate" >"$work/Packages.cached" 2>"$work/cat-file.log" ||
        fail "lecture de Packages en cache impossible"
    [[ "$(sha256sum "$work/Packages.cached" | awk '{print $1}')" == "$PACKAGES_SHA256" ]] ||
        fail "Packages APT en cache différent de la livraison signée"
    cached_count=$((cached_count + 1))
done <"$work/pkg-cache.paths"
[[ "$cached_count" -gt 0 ]] || fail "Packages absent du cache APT"

echo "Dépôt Apache StackX $DIST configuré ; clé et index vérifiés."
echo "Aucun paquet installé, aucun service redémarré."
echo "Vérifier puis lancer séparément l'installation voulue, par exemple :"
echo "  apt-cache policy apache2 apache2-bin"
echo "  apt-get --simulate --no-remove install apache2=$APACHE_VERSION apache2-bin=$APACHE_VERSION"
