#!/bin/bash
set -euo pipefail

BASE_URL="https://apt.oxmc.me/personal"
KEY_URL="https://apt.oxmc.me/personal/public.gpg"
KEYRING="/usr/share/keyrings/oxmc-apt-personal.gpg"
OUTPUT_MAIN="/etc/apt/sources.list.d/oxmc-apt-personal.list"
OUTPUT_SEC="/etc/apt/sources.list.d/oxmc-apt-personal-security.list"
DEFAULT_DISTRO="trixie"

# raspbian-addons repo (only added on Raspberry Pi)
RA_BASE_URL="https://apt.oxmc.me/raspbian-addons"
RA_KEY_URL="https://apt.oxmc.me/raspbian-addons/public.gpg"
RA_KEYRING="/usr/share/keyrings/raspbian-addons.gpg"
RA_OUTPUT="/etc/apt/sources.list.d/raspbian-addons.sources"
RA_FINGERPRINT="8A68D7B15DAE71F0B3C18D166BF9F2CD2A5611A6"

SUDO=""; [ "$(id -u)" -ne 0 ] && SUDO="sudo"

command -v dpkg >/dev/null || { echo "This is not a Debian-based system."; exit 1; }

fetch() {
    if command -v curl >/dev/null; then curl -fsSL "$1"; else wget -qO- "$1"; fi
}

# Returns the components a suite publishes (empty if the suite does not exist)
# Usage: suite_components <suite> [base_url]
suite_components() {
    fetch "${2:-$BASE_URL}/dists/$1/Release" 2>/dev/null | awk -F': ' '/^Components:/{print $2}' || true
}

# -----------------------------
# Detect distro
# -----------------------------
OS_ID="unknown"; OS_LIKE=""; CODENAME=""
if [ -f /etc/os-release ]; then
    . /etc/os-release
    OS_ID="${ID:-unknown}"
    OS_LIKE="${ID_LIKE:-}"
    case "$OS_ID $OS_LIKE" in
        *ubuntu*) CODENAME="${UBUNTU_CODENAME:-${VERSION_CODENAME:-}}" ;;
        *)        CODENAME="${DEBIAN_CODENAME:-${VERSION_CODENAME:-}}" ;;
    esac
fi

DISTRO="$DEFAULT_DISTRO"
if [ -n "$CODENAME" ] && [ -n "$(suite_components "$CODENAME")" ]; then
    DISTRO="$CODENAME"
else
    echo "No '$CODENAME' suite in the repo. Falling back to '$DEFAULT_DISTRO'."
fi

# -----------------------------
# Detect architecture & platform
# -----------------------------
ARCH=$(dpkg --print-architecture)
MODEL=""
[ -r /proc/device-tree/model ] && MODEL=$(tr -d '\0' < /proc/device-tree/model)
AVAILABLE=" $(suite_components "$DISTRO") "
COMPONENTS="main"
IS_PI=0
IS_RPIOS=0
# Raspberry Pi OS already gets the Pi core packages (firmware, eeprom, utils)
# from archive.raspberrypi.com, so we must not enable our mirror 'rpi' component there.
if [ -f /etc/rpi-issue ] || grep -rqs "raspberrypi.com" /etc/apt/sources.list /etc/apt/sources.list.d/; then
    IS_RPIOS=1
fi

add_comp() {  # only add components the suite really publishes
    case "$AVAILABLE" in *" $1 "*) COMPONENTS="$COMPONENTS $1" ;; esac
}

# Platform component: Pi, VM, or PC vendor
PLATFORM="generic"
if [[ "$MODEL" == *"Raspberry Pi"* ]]; then
    PLATFORM="rpi"
    IS_PI=1
    [ "$IS_RPIOS" -eq 1 ] || add_comp rpi   # shared mirror component: Debian-on-Pi only
    case "$MODEL" in
        *"Compute Module 4"*|*"Compute Module 5"*) add_comp rpi-compute-modern ;;
        *"Raspberry Pi 3"*)                        add_comp rpi3 ;;
        *"Raspberry Pi 4"*|*"Raspberry Pi 400"*)   add_comp rpi4 ;;
        *"Raspberry Pi 5"*)                        add_comp rpi5 ;;
        *) echo "Unknown Pi model. Using common 'rpi' only." ;;
    esac
else
    VIRT=$(systemd-detect-virt --vm 2>/dev/null || true)
    if [ -n "$VIRT" ] && [ "$VIRT" != "none" ]; then
        PLATFORM="vm"
    else
        DMI=/sys/class/dmi/id
        V=$(cat $DMI/sys_vendor 2>/dev/null || cat $DMI/board_vendor 2>/dev/null || true)
        V=$(echo "$V" | tr '[:upper:]' '[:lower:]')
        case "$V" in
            *dell*)               PLATFORM="dell" ;;
            hp*|*hewlett*)        PLATFORM="hp" ;;
            *lenovo*)             PLATFORM="lenovo" ;;
            *asus*)               PLATFORM="asus" ;;
            *framework*)          PLATFORM="framework" ;;
            *"micro-star"*|*msi*) PLATFORM="msi" ;;
            *) PLATFORM="generic" ;;
        esac
    fi
    [ "$PLATFORM" != "generic" ] && add_comp "$PLATFORM"

    # CPU component (bare metal x86 only): intel or amd
    case "$(awk '/^vendor_id/{print $3; exit}' /proc/cpuinfo 2>/dev/null || true)" in
        GenuineIntel)  add_comp intel ;;
        AuthenticAMD)  add_comp amd ;;
    esac
fi

echo "Distro       : $OS_ID ($CODENAME) -> suite $DISTRO"
echo "Architecture : $ARCH"
echo "Platform     : $PLATFORM (${MODEL:-no device-tree model})"
echo "Components   : $COMPONENTS"

# -----------------------------
# GPG key
# -----------------------------
echo "Adding GPG key..."
$SUDO mkdir -m 0755 -p "$(dirname "$KEYRING")"
fetch "$KEY_URL" | gpg --dearmor | $SUDO tee "$KEYRING" > /dev/null
$SUDO chmod 644 "$KEYRING"

# -----------------------------
# Main sources
# -----------------------------
echo "deb [arch=$ARCH signed-by=$KEYRING] $BASE_URL $DISTRO $COMPONENTS" \
    | $SUDO tee "$OUTPUT_MAIN" > /dev/null

# -----------------------------
# Security sources (only if that suite exists)
# -----------------------------
SEC_SUITE="${DISTRO}-security"
SEC_AVAILABLE=" $(suite_components "$SEC_SUITE") "
if [ "$SEC_AVAILABLE" != "  " ]; then
    SEC_COMPONENTS=""
    for c in $COMPONENTS system; do
        case "$SEC_AVAILABLE" in *" $c "*) SEC_COMPONENTS="$SEC_COMPONENTS $c" ;; esac
    done
    echo "deb [arch=$ARCH signed-by=$KEYRING] $BASE_URL $SEC_SUITE ${SEC_COMPONENTS# }" \
        | $SUDO tee "$OUTPUT_SEC" > /dev/null
else
    $SUDO rm -f "$OUTPUT_SEC"
fi

# -----------------------------
# raspbian-addons (Raspberry Pi only; trixie or bookworm)
# -----------------------------
if [ "$IS_PI" -eq 1 ]; then
    RA_SUITE=""
    case "$CODENAME" in
        trixie|bookworm) RA_SUITE="$CODENAME" ;;
    esac

    if [ -n "$RA_SUITE" ] && [ -n "$(suite_components "$RA_SUITE" "$RA_BASE_URL")" ]; then
        echo "Raspberry Pi detected. Adding raspbian-addons ($RA_SUITE)..."
        fetch "$RA_KEY_URL" | gpg --dearmor | $SUDO tee "$RA_KEYRING" > /dev/null
        $SUDO chmod 644 "$RA_KEYRING"

        # Sanity check the signing key fingerprint
        GOT_FPR=$(gpg --show-keys --with-colons "$RA_KEYRING" 2>/dev/null | awk -F: '/^fpr:/{print $10; exit}' || true)
        if [ -n "$GOT_FPR" ] && [ "$GOT_FPR" != "$RA_FINGERPRINT" ]; then
            echo "WARNING: raspbian-addons key fingerprint mismatch."
            echo "  expected: $RA_FINGERPRINT"
            echo "  got     : $GOT_FPR"
            echo "Not adding raspbian-addons."
            $SUDO rm -f "$RA_KEYRING" "$RA_OUTPUT"
        else
            $SUDO tee "$RA_OUTPUT" > /dev/null <<SRC
Types: deb
URIs: $RA_BASE_URL
Suites: $RA_SUITE
Components: main
Signed-By: $RA_KEYRING
SRC
        fi
    else
        echo "No raspbian-addons suite for '${CODENAME:-unknown}' (needs trixie or bookworm). Skipping."
    fi
fi

# -----------------------------
# Clean up the old firmware pin from earlier versions of this script
# -----------------------------
$SUDO rm -f /etc/apt/preferences.d/oxmc-apt-personal-rpi-firmware

$SUDO apt update
echo "Done. Suite $DISTRO ($ARCH), components: $COMPONENTS"
