#!/bin/bash
# from http://askubuntu.com/a/450092, tweaked

pollTime=60
export DISPLAY=:0
DIR=/var/lib/timelimit
shutdown_warning=5 # minutes
logout_warning=60  # seconds

while(true); do
	sleep $pollTime
	usersLogedIn=$( users|sed -e 's/\s\+/\n/g'|sort|uniq )
	if [ `date +%H` -ge 23 -o `date +%H` -lt 6 ]; then
#	if [ `date +%H` -ge 1 -a `date +%H` -lt 6 ]; then
		for userName in $usersLogedIn; do
			export XAUTHORITY=/home/$userName/.Xauthority
			notify-send --icon=gtk-dialog-warning --urgency=critical -t 30000 "$userName" "Shutdown in $shutdown_warning minutes!"
		done
		shutdown -h +$shutdown_warning
	fi
	for userName in $usersLogedIn; do
		timeFile=$DIR/$userName.time
		limitFile=$DIR/$userName.limit
		if [[ -e "$limitFile" ]]
		then
			timeLimit=`cat $DIR/$userName.limit`
			if [[ ! -e "$timeFile" || `( stat -c '%z' "$timeFile" | cut -c1-10 )` != `date -I` ]]
			then 
				timeUsed=$pollTime
			else
				timeUsed=$(( `cat "$timeFile"` + $pollTime ))
			fi
			echo $timeUsed > "$timeFile"
			if [[ $timeUsed -ge $timeLimit ]]
			then
				export XAUTHORITY=/home/$userName/.Xauthority
				notify-send --icon=gtk-dialog-warning --urgency=critical -t 30000 "$userName" "You have $logout_warning seconds left!"
				sleep $logout_warning
				pkill -u $userName
			else
				minutesLeft=$(( ( $timeLimit - $timeUsed ) / 60 ))
				if [ $(( $minutesLeft % 5 )) = 0 ]; then
					notify-send --icon=gtk-dialog-info --urgency=low -t 5000 "$userName" "You have $minutesLeft minutes remaining."
				fi
			fi
		fi
	done
done
