#!/bin/bash
# Force Debian Bookworm (12) repos and block upgrades to newer releases

set -e

DEBIAN_MIRROR="http://ftp.debian.org/debian"

# --- Step 1: Fix sources.list files ---
for file in /etc/apt/sources.list /etc/apt/sources.list.d/*.list; do
    [ -f "$file" ] || continue

    # Replace "stable" with "bookworm"
    if grep -qE "deb\s+$DEBIAN_MIRROR\s+stable\b" "$file"; then
        sed -i.bak -E "s|(deb\s+$DEBIAN_MIRROR\s+)stable\b|\1bookworm|g" "$file"
        echo "Updated $file: replaced 'stable' with 'bookworm'"
    fi

    # Replace "stable-security" with "bookworm-security"
    if grep -qE "deb\s+http://security\.debian\.org/debian-security\s+stable-security\b" "$file"; then
        sed -i.bak -E "s|(deb\s+http://security\.debian\.org/debian-security\s+)stable-security\b|\1bookworm-security|g" "$file"
        echo "Updated $file: replaced 'stable-security' with 'bookworm-security'"
    fi
done

# --- Step 2: block Trixie  releases ---
cat >/etc/apt/preferences.d/99-block-trixie.pref <<'EOF'
# Block Debian 13 Trixie
Package: *
Pin: release n=trixie
Pin-Priority: -1

EOF

echo "Created /etc/apt/preferences.d/bookworm.pref (Trixie blocked)."

# --- Step 3: Update apt cache ---
sudo apt update -y
