#!/bin/sh

# upgrade_debian.sh
# 2025-08-18
# by Gernot Walzl

# This script upgrades Debian to a new release.

. /etc/os-release

TARGET_VERSION_ID=${TARGET_VERSION_ID:-'13'}
TARGET_VERSION_CODENAME=${TARGET_VERSION_CODENAME:-'trixie'}

URL_DEFAULTS='https://gernot-walzl.at/Debian/defaults'
DEFAULT_PKGS_MANUAL="debian${TARGET_VERSION_ID}_clean-install_apt-mark_showmanual.txt"
DEFAULT_PKGS_AUTO="debian${TARGET_VERSION_ID}_clean-install_apt-mark_showauto.txt"

fetch_default_pkgs () {
  mkdir defaults
  wget -O "defaults/$DEFAULT_PKGS_MANUAL" "$URL_DEFAULTS/$DEFAULT_PKGS_MANUAL"
  wget -O "defaults/$DEFAULT_PKGS_AUTO" "$URL_DEFAULTS/$DEFAULT_PKGS_AUTO"
}

update_apt_sources () {
  mv /etc/apt/sources.list /etc/apt/sources.list.bak
  sed "/^deb/ s/$VERSION_CODENAME/$TARGET_VERSION_CODENAME/g" \
    /etc/apt/sources.list.bak \
    > /etc/apt/sources.list
  apt update
}

upgrade_all_pkgs () {
  apt full-upgrade
}

check_inet () {
  ping -q -c1 deb.debian.org
}

install_default_pkgs () {
  apt install $(grep -v '^task-' "defaults/$DEFAULT_PKGS_MANUAL")
  if [ "$(apt-mark showmanual | grep '^task-')" = \
      "$(grep '^task-' "defaults/$DEFAULT_PKGS_MANUAL")" ]; then
    apt install --mark-auto $(cat "defaults/$DEFAULT_PKGS_AUTO")
  fi
  apt-mark auto $(cat "defaults/$DEFAULT_PKGS_AUTO")
}

remove_obsolete () {
  apt purge '?obsolete'
  apt autoremove
  apt purge '?config-files'
}

show_changed_config () {
  apt install debsums
  debsums -es
}

echo
echo "UPGRADE DEBIAN"
echo "Currently installed version: $VERSION_ID ($VERSION_CODENAME)"
echo "Target version to install:   $TARGET_VERSION_ID ($TARGET_VERSION_CODENAME)"
echo
echo "Press Enter to continue."
read CONTINUE
if [ "$VERSION_ID" -ne "$TARGET_VERSION_ID" ]; then
  fetch_default_pkgs
  update_apt_sources
  upgrade_all_pkgs
  if check_inet; then
    install_default_pkgs
  fi
  echo
  echo "The system will reboot now."
  echo "Rerun this script afterwards to install default packages"
  echo "and to remove obsolete packages."
  echo
  echo "Press Enter to continue."
  read CONTINUE
  reboot
else
  install_default_pkgs
  remove_obsolete
  show_changed_config
fi