#!bin/bash

# Check that there is a single param given to this script
if [ $# -ne "1" ]
then
	echo "Lifetime in second is the only expected param."
	exit 1
fi

# Regex to match integers
regex='^[0-9]+$'

# Check if the given param is an integer
if ! [[ ${1} =~ ${regex} ]]
then
	echo "Lifetime in second as to be an Integer."
	exit 1
fi

# Get all the ssh (sshd) running process, filtred with @pts to get ssh sessions, formated as such:
# "<timestamp> <pid> sshd: <session>"
process_list=`ps -eo etimes,pid,cmd --sort=etimes | grep sshd | grep '@pts' | sed -r "s/[[:space:]]+/\\ /g"`

# Check if the process list is empty, if so, there is no sshd session openned, we can exit safely
if [ -z "${process_list}" ]
then
	exit 0
fi

# Variable for seconds conversion to minutes
minute=60

# Split the process list line by line to process it
while IFS=' ' read -r timestamp pid app user
do
	if [ "${timestamp}" -gt ${1} ]; then
		if [[ ${user} == charlie@* ]]; then
			kill -HUP ${pid}
			echo "Killed: ${timestamp} ${pid} ${app} ${user}"
		fi
	fi

done <<< $process_list
