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