#!/bin/bash

#####################################################################
# @description:                                                     #
#   Debian 10 to Debian 11 upgrade tool for basic debian 10 system  #
#                                                                   #
# @author: Bram Prieshof                                            #
#####################################################################

#ScriptVars
UpgradeDist=deb11
InstalledOptions=("${SelectedOptions[@]}" "${EnabledAons[@]}")
Sysup2Date=no

#OS Detection
dist_ver=$(grep --color=never -Po "^VERSION_ID=\K.*" "/etc/os-release")
dist=$(grep --color=never -Po "^ID=\K.*" "/etc/os-release")

if [[ "${dist}" == *"debian"* ]] && [[ "${dist_ver}" == *"10"* ]]; then
 CurDist=deb10
else
 echo "This OS in not eligible for this upgrade"
 exit
fi

#PackageManager-config
PKGM=apt
PKGUC="$PKGM update"
PKGUP="$PKGM upgrade -y"
PKGI="${PKGM} install -y --no-install-recommends"

#Update current release
if [ $Sysup2Date = no ]; then
    echo "The system will now update the packages for the current release"
    read -r -s -p $'Press enter to continue, or ctrl+c to quit'
    $PKGUC
    DEBIAN_FRONTEND=noninteractive $PKGUP -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold"
    $PKGM dist-upgrade -y
    $PKGM clean all
    $PKGM autoremove -y
    sed -i -e '/Sysup2Date=no/c\Sysup2Date=yes' "$0"
    echo "The current release is up to date,"
    echo "please reboot the system and re-run this scipt to continue"
    exit
fi

echo "The system will now update the repositories to the new release and update all packages"
read -r -s -p $'Press enter to continue, or ctrl+c to quit'

#Update Debian repo's
sed -i -e 's/buster/bullseye/g' -e 's#http://security.debian.org/debian-security#https://deb.debian.org/debian-security#g' -e 's#http://security.debian.org#https://deb.debian.org/debian-security#g' -e 's#bullseye/updates#bullseye-security#g'   /etc/apt/sources.list
#Update Hetzner mirrror repo's
sed -i -e 's/buster/bullseye/g' /etc/apt/sources.list.d/hetzner* -e 's#bullseye/updates#bullseye-security#g' /etc/apt/sources.list.d/hetzner*

#Running updates
$PKGM update
DEBIAN_FRONTEND=noninteractive $PKGUP --without-new-pkgs -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold"
DEBIAN_FRONTEND=noninteractive $PKGM full-upgrade -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold"
$PKGM autoremove -y

echo "Upgrade finished, please reboot the system"
