#!/bin/bash
#
# this is a sample script that show a desktop notification
# when your system upgrades are done
#
# a better GUI to systemd timers (like the KDE Weather/Calendar applet)
# would be better
#
# in run-parts mode this would have gone to /etc/cron.daily/
# with a splitted cron-daily, it should be appended
# to apt-daily-{upgrade}.service like this:
#    ExecStartPost=/etc/site/zz_desktop_notification
#

set -e
[ -e /var/log/unattended-upgrades/unattended-upgrades.log ] || exit 0

line=$(grep "will be upgrade" /var/log/unattended-upgrades/unattended-upgrades.log | tail -n 1)
if [ -z "$line" -a -e /var/log/unattended-upgrades/unattended-upgrades.log.1.gz ]
then
	line=$(zgrep "will be upgraded" /var/log/unattended-upgrades/unattended-upgrades.log.1.gz | tail -n 1)
fi

updated=$(echo "$line" | grep ^$(date +%Y-%m-%d) | cut -d: -f4)

# reboot-required isn't broad enough to my taste (mostly only kernel);
# these are the usual suspects that might make a system
# unbootable or make X doens't come up
for a in $updated; do
	if [[ $a == *grub* ]]; then grub="$grub $a"; fi
	if [[ $a == *systemd* ]]; then systemd="$systemd $a"; fi
	if [[ $a == *radeon* ]]; then radeon="$radeon $a"; fi
	if [[ $a == *mesa* ]]; then mesa="$mesa $a"; fi
done;

if [ -e /var/run/reboot-required -o -n "$grub" -o -n "$systemd" -o -n "$radeon" -o -n "$mesa" ]
then
	# check if user is active
	if [ -n "$(users)" ]
	then
		echo "grub:$grub"
		echo "systemd:$systemd"
		echo "radeon:$radeon"
		echo "mesa:$mesa"
		echo "user(s) active:"
		who
		users=$(loginctl list-sessions | grep seat0 | awk '{print $3}')
		if [ -n "$users" ]
		then
			for user in $users
			do
				export DISPLAY=:0
				su "$user" -c "notify-send 'REBOOT NEEDED' -i dialog-warning \"$updated\" "
			done
		else
			echo "REBOOT NEEDED: $updated" | wall
		fi
	else
                # reboot after 1 minute
                shutdown --reboot
	fi
else
	# check if a graphical session exists
	users=$(loginctl list-sessions | grep seat0 | awk '{print $3}')
	if [ -n "$users" ]
	then
	    export DISPLAY=:0
            if [ -n "$updated" ]
            then
		for user in $users
		do
			echo "$user"
			su "$user" -c "notify-send 'daily upgrade completed' -i dialog-information \"$updated\" "
		done
	    else
		for user in $users
		do
			su "$user" -c "notify-send 'cron-daily finished' -i dialog-information 'nothing to update today'"
		done
	    fi
	fi
fi
