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