#!/bin/sh
# -------
# File:        session-cmd-exec
# Description: session-cmd backend
# Author:      Luis Garcia Gisbert <garcia_luigis@gva.es>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin St, Fifth Floor, Boston MA 02110-1301 USA
# --------


set -e

[ -r /etc/tcos/tcos.conf ] && . /etc/tcos/tcos.conf

# title of popup
TITLE="TCOS"

# icon to show in popup
ICON_FILE="/usr/share/pixmaps/tcos-icon-32x32.png"

MODE=$1
shift

# timeout for popup (in seconds)
LOGOUT_TIMEOUT=20
[ $# -gt 1 ] && LOGOUT_TIMEOUT=$1 && shift


# message to show in popup
LOGOUT_MESSAGE="Session will close in $LOGOUT_TIMEOUT seconds"
POWEROFF_MESSAGE="Pc will shutdown in $LOGOUT_TIMEOUT seconds"
REBOOT_MESSAGE="Pc will reboot in $LOGOUT_TIMEOUT seconds"

case ${MODE} in
   POWEROFF)
      POWEROFF_MESSAGE="$*"
      ;;
   REBOOT)
      REBOOT_MESSAGE="$*"
      ;;
   LOGOUT)
      LOGOUT_MESSAGE="$*"
      ;;
esac

if [ -d /etc/tcos/conf.d/ ]; then
  for file in /etc/tcos/conf.d/session-cmd*; do
    [ -e $file ] && . $file
  done
fi


MESSAGE_CMD="notify-send -u normal -t $(($LOGOUT_TIMEOUT * 1000)) -i ${ICON_FILE} ${TITLE}"


message(){
   $MESSAGE_CMD "$1" 2>/dev/null
}

socket_basename(){
   echo "$(id -un)"
}

case ${MODE} in
   MESSAGE)
      if [ "$*" ] ; then
         message "$*"
      fi
      ;;
   POWEROFF)
      message "$POWEROFF_MESSAGE"
      ;;
   REBOOT)
      message "$REBOOT_MESSAGE"
      ;;
   LOGOUT)
      message "$LOGOUT_MESSAGE"
      sleep $LOGOUT_TIMEOUT
      if [ `ps -U $(socket_basename) | grep -c -e "ksmserver" -e "start_kdeinit"` -eq 2 ];then
          dcop ksmserver default logout 0 -1 -1
      else
          if [ $(gnome-session-save --help | grep -c force-logout) -ge 1 ]; then 
             gnome-session-save --force-logout
          else
             gnome-session-save --kill --silent
          fi
      fi
      ;;
   NOSCREENSAVER)
      if [ `ps -U $(socket_basename) | grep -c -e "ksmserver" -e "start_kdeinit"` -eq 2 ];then
          dcop kdesktop KScreensaverIface quit
      fi
      if [ -f /usr/bin/gnome-screensaver-command ];then
          gnome-screensaver-command -d
      elif [ -f /usr/bin/xscreensaver-command ];then
          xscreensaver-command --deactivate
      fi
      ;;
   OPEN)
      if [ "$*" ] ; then
         [ -x /usr/bin/gnome-open ] && gnome-open "$*" 2>/dev/null
      fi
      ;;
esac
exit 0
