#!/bin/bash

set -e
set -u

USER_PKGS_BEFORE=$(dnf -q repoquery --userinstalled --qf '%{name}')

dnf clean all
dnf install task-iso-plasma5-conflicts --allowerasing --assumeyes
dnf remove  task-iso-plasma5-conflicts --assumeyes
dnf install task-iso-plasma6 --allowerasing --assumeyes
dnf dsync --allowerasing --assumeyes
dnf remove update-kde5-to-kde6 gdm-default-to-xorg dm-scripts --assumeyes

AVAILABLE_PKGS=$(dnf -q repoquery --qf '%{name}')
USER_PKGS_AFTER=$(dnf -q repoquery --userinstalled --qf '%{name}')
REMOVED_USER_PKGS=$(
    comm -23  \
        <(sort <<< "$USER_PKGS_BEFORE") \
        <(sort <<< "$USER_PKGS_AFTER")
)

USER_PKGS_TO_RESTORE=''
while read -r pkg; do
    [ -z "$pkg" ] && continue
    if grep -qFx "plasma6-${pkg}" <<< "$AVAILABLE_PKGS"; then
        USER_PKGS_TO_RESTORE+=" plasma6-${pkg}"
    fi
done <<< "$REMOVED_USER_PKGS"

if [ -n "$USER_PKGS_TO_RESTORE" ]; then
    #shellcheck disable=2086
    dnf install $USER_PKGS_TO_RESTORE --assumeyes
fi

echo
echo "The upgrade to KDE 6 completed successfully!"
echo "The system is rebooting..."
sleep 3
reboot
