#!/bin/bash
#
# This script set the shell's timeout through the use
# of $HOME/.ssh/environment file. The environment variable
# TMOUT will be set in here and read by SSH.
# The PermitUserEnvironment has to be set to yes in /etc/ssh/sshd_config
# You must run this as root, and you cannot set session timeout on root
#

usage()
{
  echo "Usage: sessiontimeout  -l | -m -u <username> -t <timeout value>"
  echo "           where   -l       list session timeout for given user"
  echo "                   -m       modify/set session timeout for given user"
  echo "           	   -u       user name to list or set session timeout"
  echo "           	   -t       session timeout in seconds"

  exit 1
}
listTimeout()
{
   if [ ! -f /home/$1/.ssh/environment ]; then
      echo -n 0
      return
   fi
   grep -q TMOUT /home/$1/.ssh/environment
   if [ $? -ne 0 ]; then
      echo -n 0
      return
   fi
   timeout=`cat /home/$1/.ssh/environment | grep TMOUT | cut -d'=' -f2`
   echo -n $timeout
}
setTimeout()
{
   echo "TMOUT=$2" > /home/$1/.ssh/environment
   chmod 644 /home/$1/.ssh/environment
   chown root.hmc /home/$1/.ssh/environment
}

export LANG=en_US
export PATH=/bin:/usr/bin:$PATH
showHelp=0
while getopts 'mlu:t:' optname; do
  case "$optname" in
    l) OPTYPE=l;;
    m) OPTYPE=m;;
    u) USER="$OPTARG";;
    t) TIMEOUT="$OPTARG";;
    *) showHelp=1; break;;
  esac
  noopt=0
done
if [ $showHelp -eq 1 ]; then
   usage
fi
if [ "$OPTYPE" == "l" ]; then
   listTimeout $USER
   exit 0
fi
if [ "$OPTYPE" == "m" ]; then
  setTimeout $USER $TIMEOUT
  exit 0
fi

exit 0
