d4a401
#!/bin/sh
d4a401
d4a401
PATH=/sbin:/bin:/usr/bin
d4a401
d4a401
# Check session status using systemd
d4a401
session_ids=$(systemd-loginctl list-sessions 2>/dev/null | awk '{print $1}')
d4a401
for session in ${session_ids} ; do
d4a401
	session_status=$(systemd-loginctl session-status ${session})
d4a401
	echo "${session_status}" | grep -e '\(Active: yes\|State: active\)' &> /dev/null &&
d4a401
		echo "${session_status}" | grep -e '\(gnome-settings-daemon\|kded4\|xfce4-power-manager\)' &> /dev/null && exit 0
d4a401
done
d4a401
d4a401
# Get the ID of the first active X11 session: using ConsoleKit
d4a401
uid_session=$(
d4a401
ck-list-sessions 2>/dev/null | \
d4a401
awk '
d4a401
/^Session[0-9]+:$/ { uid = active = x11 = "" ; next }
d4a401
{ gsub(/'\''/, "", $3) }
d4a401
$1 == "unix-user" { uid = $3 }
d4a401
$1 == "active" { active = $3 }
d4a401
$1 == "x11-display" { x11 = $3 }
d4a401
active == "TRUE" && x11 != "" {
d4a401
	print uid
d4a401
	exit
d4a401
}')
d4a401
d4a401
# Check that there is a power manager, otherwise shut down.
d4a401
[ "$uid_session" ] &&
d4a401
ps axo uid,cmd | \
d4a401
awk '
d4a401
    $1 == '$uid_session' &&
d4a401
	($2 ~ /gnome-power-manager/ || $2 ~ /kpowersave/ ||
d4a401
	 $2 ~ /xfce4-power-manager/ || $2 ~ /\/usr\/libexec\/gnome-settings-daemon/ ||
d4a401
	 $2 ~ /kded4/ || $3 ~ /guidance-power-manager/) \
d4a401
		{ found = 1; exit }
d4a401
    END { exit !found }
d4a401
' ||
d4a401
  shutdown -h now
d4a401