#!/bin/bash
#
# logout idle users and shutdown machine
#
set -eu

action="systemctl poweroff"
uptime=$(cat /proc/uptime | cut -f1 -d.)
maxidle=3600  ## seconds

u=($(loginctl list-users --no-legend  | sort -hr | head -1))
una=${u[1]:-''}
uid=${u[0]:-''}

talk2dbus() {
    local display=":$(ls /tmp/.X11-unix/* | sed 's#/tmp/.X11-unix/X##' | head -n 1)"
    sudo -u $una DISPLAY=$display \
	 DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$uid/bus "$@"
}

########

## shutdown if nobody is loged in:
if [[ -z "$una" ]] || [[ $uid -lt 1000 ]] ; then
  exec $action
fi

# FIXME: find idle time independent of running screensaver
if ! t=$(talk2dbus qdbus org.kde.screensaver /ScreenSaver GetActiveTime) ; then
    echo "No graphical logins found."
else
    idle=$(( t / 1000 ))
    if [[ $idle -gt $maxidle ]] && [[ ! -d "/srv/samba/schools/default-school/teachers/" ]] ; then
        talk2dbus notify-send -i system-shutdown -u critical -a 'Important System Information' \
	          'Please log out, the system will shut down soon!' \
	          'There has been no activity for too long.'
        ## shutdown:
        #talk2dbus qdbus org.kde.ksmserver /KSMServer logout 1 2 0
        ## logout:
        talk2dbus qdbus org.kde.ksmserver /KSMServer logout 1 0 0 || \
	    loginctl terminate-user $una
        echo "Log-out user $una after being idle for $idle seconds."
    else
        echo "The user $una has been idle for $idle seconds."
    fi
fi

#w -s | grep tty | sed "s/[[:space:]]\+/ /g" | cut -f4 -d ' '
