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