#!/bin/bash
# Detect Mac OS Idle and force-autologout
# Regular auto-logout is too "polite" and won't quit if user accidentally left
# any apps open.  This is more authoritive.
# Carl Chan 100707

####### Options #######
# Timeouts all in seconds
# Max idle time before forcing logout
maxidle_default=1800
# Final warning dialog box timeout
warning_timeout=10

function do_on_maxidle() {
	give_final_warning 2>&1 >>/dev/null
	if [ $? -eq 1 ]; then
		exit 0
	else
		killall -9 loginwindow
	fi
}
#######################

function give_final_warning(){
	osascript <<EOF
		tell application "System Events"
			display dialog "Final logout warning: This workstation has been idle for more than $(($maxidle/60)) minutes. Click cancel to stop auto-logout." buttons "Cancel" giving up after $warning_timeout with icon 0
		end tell
EOF
}

# Override script default if AutoLogOutDelay is set from Directory Server
if [ -e "/Library/Managed\ Preferences/.GlobalPreferences" ]; then
	maxidle_managed=$(defaults read /Library/Managed\ Preferences/.GlobalPreferences | grep "AutoLogOutDelay" | sed "s/[^0-9]//g")
fi

if [ -z "$maxidle_managed" ]; then
	maxidle="$maxidle_default"
else
	maxidle="$maxidle_managed"
fi

# Really cool way for finding idle time
# Modified from http://www.macosxhints.com/dlfiles/idle_time_check.txt
# perl expression didn't work and i don't know perl well enough to fix it
# so stuck with slightly clunkier method, but should be ok since this script
# isn't running continuously in the background
idletime=$(($(ioreg -c IOHIDSystem | grep -m1 HIDIdleTime | sed 's/[^0-9]//g')/1000000000))

# Check idle time and force logout if idletime > maxidle
if [ "$idletime" -gt "$maxidle" ]; then
	do_on_maxidle
fi

exit 0


