#!/bin/bash

# Script to upgrade SolydXK 10 to SolydXK 11
# Arjen Balfoort, 08-08-2021

# Packages that deborphan must NOT treat as orphans - comma separated list
# Set to '*' to keep everything
NOTORPHAN=''

# ===========================================================

# Check if this script is run as root
if [ $UID -ne 0 ]; then
  echo 'Please, type root password...'
  su -c "$0 $@"
  exit
fi

# Save user name
UNM=$(logname)

# Save log file
LOG="/home/$UNM/solydxk11-upgrade.log"

# In SolydX 10 PATH is incomplete
export PATH=/usr/local/sbin:/usr/sbin:/sbin:$PATH

# Get version
XK='solydx'; [ -e '/usr/bin/kdeinit5' ] && XK='solydk'
echo -e "\n>>> Start $XK upgrade to SolydXK 11 (Debian Bullseye)\n" | tee "$LOG"
echo "    Log: $LOG" | tee -a "$LOG"

# Ask user for an unattended upgrade
APT='apt-get'
echo
read -p "Do you feel brave enough to run an unattended upgrade (y/N)?" ANSWER
case "$ANSWER" in 
    y|Y )
        # Make this script unattended
        # https://debian-handbook.info/browse/stable/sect.automatic-upgrades.html
        export DEBIAN_FRONTEND=noninteractive
        APT="yes '' | apt-get -y -o DPkg::options::=--force-confdef -o DPkg::options::=--force-confold"
        echo "    User selected unattended upgrade." | tee -a "$LOG"
        ;;
esac

# Fix apt
echo -e '\n>>> Fix apt in case of broken installs\n' | tee -a "$LOG"
dpkg --configure -a
apt-get install -f

# Pre-seeds for debconf
echo -e '\n>>> Pre-seed debconf (fix db first)\n' | tee -a "$LOG"
FIXDB='/usr/share/debconf/fix_db.pl'; [ -f "$FIXDB" ] && perl "$FIXDB" | tee -a "$LOG"
echo 'keyboard-configuration keyboard-configuration/model select Generic 105-key (Intl) PC' | debconf-set-selections
echo 'samba-common samba-common/dhcp boolean true' | debconf-set-selections

# minissdpd will throw systemd service errors if not configured correctly
NETWINT=$(ip link show | awk '/state UP/ {print $2}' | sed 's/.$//')
if [ "$NETWINT" ]; then
    echo -e "\n>>> Pre-seed minissdpd with network interface: $NETWINT\n" | tee -a "$LOG"
    echo 'minissdpd minissdpd/start_daemon boolean true' | debconf-set-selections
    echo "minissdpd minissdpd/listen string $NETWINT" | debconf-set-selections
else
    echo -e '\n>>> Cannot find network interface: remove minissdpd' | tee -a "$LOG"
    echo -e '    minissdpd will be re-installed after the dist-upgrade\n' | tee -a "$LOG"
    eval $APT purge minissdpd | tee -a "$LOG"
fi

echo -e '\n>>> Make sure the system is up-to-date\n' | tee -a "$LOG"
apt-get update | tee -a "$LOG"
eval $APT dist-upgrade | tee -a "$LOG"

echo -e '\n>>> Point sources.list to solydxk-11/bullseye repositories\n' | tee -a "$LOG"
sed -i '{
s|http://security.debian.org|https://security.debian.org/debian-security|g
s|/updates|-security|g
s|buster|bullseye|g
s|testing|bullseye|g
s|solydxk[0-9e-]\+|solydxk-11|g
}' /etc/apt/sources.list
cat /etc/apt/sources.list | tee -a "$LOG"

echo -e '\n>>> Upgrade to SolydXK 11/Debian Bullseye' | tee -a "$LOG"
echo -e '        Fonts and theme may change during upgrade but it will be fine after reboot\n' | tee -a "$LOG"
apt-get update
eval $APT upgrade | tee -a "$LOG"
echo -e '\n>>> Finally run dist-upgrade\n' | tee -a "$LOG"
eval $APT dist-upgrade | tee -a "$LOG"

# If minissdpd was removed, install it now and let the user configure it
if [ -z "$NETWINT" ]; then
    apt-get install minissdpd
fi

echo -e '\n>>> Install/replace packages\n' | tee -a "$LOG"
if [ "$XK" == 'solydx' ]; then
    eval $APT purge solydxee-info | tee -a "$LOG"
    eval $APT install solydx-system-adjustments-11 | tee -a "$LOG"
else
    eval $APT purge solydkee-info | tee -a "$LOG"
    eval $APT install solydk-system-adjustments-11 | tee -a "$LOG"
fi

# Cleanup
eval $APT purge evolvere-icon-theme*
eval $APT autoremove | tee -a "$LOG"
echo
echo -e '>>> Do you want to remove unavailable and orphaned packages?\n\n' \
'   WARNING: this will remove all packages not found in the current repositories\n' \
'            and it will remove all orphaned packages.\n\n'
read -p 'Do you want to continue  (y/N)?' ANSWER
case "$ANSWER" in 
    y|Y )
        if [ "$NOTORPHAN" != '*' ]; then
            echo -e '\n>>> Remove unavailable packages only when not manually held back\n' | tee -a "$LOG"
            for PCK in $(env LANG=C apt-show-versions | grep 'available' | cut -d':' -f1); do
                REMOVE=true
                for HELDPCK in $(env LANG=C dpkg --get-selections | grep hold$ | awk '{print $1}'); do
                    if [ $PCK == $HELDPCK ]; then
                        REMOVE=false
                    fi
                done
                if $REMOVE; then
                    if [[ "$NOTORPHAN" =~ "$PCK" ]] || [ "$NOTORPHAN" == '*' ]; then
                        echo "Not available but keep installed: $PCK" | tee -a "$LOG"
                    else
                        eval $APT purge $PCK | tee -a "$LOG"
                    fi
                fi
            done
            echo -e '\n>>> Removing orphaned packages\n' | tee -a "$LOG"
            DEBORPHAN='deborphan'
            if [ "$NOTORPHAN" ]; then
                DEBORPHAN='deborphan | sed "/"${NOTORPHAN//,/\/d;/}"/d"'
            fi
            ORPHANED=$(eval $DEBORPHAN)
            while [ "$ORPHANED" ]; do
                eval $APT purge $ORPHANED | tee -a "$LOG"
                RC=$(dpkg-query -l | sed -n 's/^rc\s*\(\S*\).*/\1/p')
                [ "$RC" ] && eval $APT purge $RC
                ORPHANED=$(eval $DEBORPHAN)
            done
        fi
        ;;
esac

# Let the user decide if python2* can be removed
PYTHON2=$(dpkg -l python2* 2>/dev/null | grep ^i)
if [ "$PYTHON2" ]; then
    echo
    echo -e '>>> Do you want to remove python2 from your system?\n\n' \
    '   WARNING: removing python2 will break any installed packages and custom scripts that depend on python2.\n' \
    '   Note that apt will ask confirmation before actually removing the listed packages.\n\n'
    read -p 'Do you want to continue  (y/N)?' ANSWER
    case "$ANSWER" in 
        y|Y )
            apt-get purge python2* | tee -a "$LOG"
            ;;
    esac
fi

echo
eval $APT autoremove | tee -a "$LOG"
apt-get clean

# Make the user the owner of the log file
chown $UNM:$UNM "$LOG"

if [ "$XK" == 'solydx' ]; then
    ICONTHEME=$(xfconf-query -c xsettings -p /Net/IconThemeName)
    if [[ $ICONTHEME == *'evolvere'* ]]; then
        echo -e '\n>>> Set evolvere-2 as the default icon theme\n' | tee -a "$LOG"
        exec su $UNM -s /bin/sh -c "xfconf-query -c xsettings -p /Net/IconThemeName -s evolvere-2"
    fi
else
    PCI=$(locate plasma-changeicons)
    if [ "$PCI" ]; then
        ICONTHEME=$(kreadconfig5 --group "Icons" --key "Theme")
        if [[ $ICONTHEME == *'evolvere'* ]]; then
            echo -e '\n>>> Set evolvere-2-blue as the default icon theme\n' | tee -a "$LOG"
            exec su $UNM -s /bin/sh -c "$PCI evolvere-2-blue"
        fi
    fi
fi
