#!/bin/bash -e
#-----------------------------------------------------------------------------
# x11tera_on_teardown
# The script to use with the x11tera 'on_terminate_session' function.
# This script is called when it is necessary to perform a logout.
#-----------------------------------------------------------------------------
echo "x11tera on-logout"

# terminate session automatically
for id in $(loginctl show-seat seat0 | grep Sessions= | cut -d'=' -f2); do
  s=$(loginctl show-session $id --p Id --p Remote --p Name --p Type --p Class --p Active --p IdleHint --p LockedHint | tr '\n' ' ' | grep Remote=no.*Class=user.*Active=yes)
  if [ ! -z "$s" ]; then
    echo "Terminate session $s"
    loginctl terminate-session $id
    if [ $(which dm-tool) ] && [ $(grep lightdm$ /etc/X11/default-display-manager) ]; then
      XDG_SEAT_PATH=/org/freedesktop/DisplayManager/Seat0 dm-tool switch-to-greeter
    fi
    exit 0
  fi
done
exit 1
