#!/usr/bin/bash
# Force anacron to run: sudo run-parts /etc/cron.daily
# apt-get update
# apt-get upgrade -y
# apt-get dist-upgrade -y
# apt autoremove -y
# apt autoclean
# apt clean

function notify-send() {
    #Detect the name of the display in use
    local display=":$(ls /tmp/.X11-unix/* | sed 's#/tmp/.X11-unix/X##' | head -n 1)"

    #Detect the user using such display
    local user=$(who | grep '('$display')' | awk '{print $1}' | head -n 1)

    #Detect the id of the user
    local uid=$(id -u $user)

    sudo -u $user DISPLAY=$display DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$uid/bus notify-send "$@"
}

logger -t uppdatera Automatiserad systemuppdatering startar
notify-send "Uppdaterar" -i gtk-dialog-warning -t 30000 "Stäng INTE av burken"
systemd-inhibit --why="Uppdaterar systemet" /usr/local/bin/update-ubuntu
needrestart -u 'NeedRestart::UI::stdio' -r a
if [ -f /var/run/reboot-required ]; then
    notify-send "Boota om" -i system-reboot -t 30000 "Uppdateringen klar. Kräver omstart."
else
    notify-send "Uppdatering klar" -i gtk-ok -t 30000 "Öppna program kan behöva omstart."
fi
logger -t uppdatera Automatiserad systemuppdatering slutförd
exit 0