#!/bin/bash

###########################################################
## Copyright (c) 2002-2024 Alexey Kuryakin daqgroup@mail.ru
###########################################################

###########################################################
## session-logout t
## Logout active local x11 session after delay t (seconds).
###########################################################

###########################################################
source $(crwkit which crwlib_base.sh); # Use base library #
source $(crwkit which crwlib_file.sh); # Use file library #
###########################################################

function list_user_sessions(){
 for sid in $(loginctl show-user $USER -p Sessions --value | xargs); do
  local type="$(loginctl show-session $sid --property=Type --value | xargs)";
  local active="$(loginctl show-session $sid --property=Active --value | xargs)";
  local remote="$(loginctl show-session $sid --property=Remote --value | xargs)";
  if [ "$type" = "x11" ] && [ "$active" = "yes" ] && [ "$remote" = "no" ]; then echo "$sid"; fi;
 done;
};

function execute(){
 echo "$@";
      "$@";
};

function main(){
 local delay=0;
 if is_number "$1"; then
  let "delay=$1";
  local sid="$(list_user_sessions | xargs)";
  if is_number $sid; then
   wall "Requested Logout $USER session $sid after $delay seconds.";
   execute sleep $delay;
   execute loginctl kill-session $sid;
  else
   fatal 1 "Error: could not find $USER x11 session.";
  fi;
 else
  echo -e "usage:\n $scriptname delay - Logout current X session after delay (seconds).\n";
 fi;
};

main "$@";

##############
## END OF FILE
##############
