#!/bin/bash
#
# Function to display/select/kill a session
#
LOC_FILE="/tmp/wout.`/bin/date +\"%s\"`"
TR=/usr/bin/tr
CUT=/usr/bin/cut

killSession() {
	i=$1
	/sbin/fuser -v /dev/${t_a[i]} >${LOC_FILE}
	fuserResult=$?
	if [ $fuserResult -ne 0 ]
	    then
		printf "\nPermission Denied! Bailing Out!\n"
		exit
	fi

	printf "\n______________________________________________________________________________\n"
	printf " USER     TTY      IDLE     LOGIN@ FROM\n"
	printf "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"
	printf " %-8.12s %-8.12s %-8.12s %-6.12s %-16.128s\n" \
	    "${u_a[i]}" "${t_a[i]}" "${i_a[i]}" "${l_a[i]}" "${f_a[i]}"
	printf "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"
	printf "Confirm Kill Session (Y/[N]): "
	read choice
	case $choice in
	    (Y|y|Yes|yes|YES) printf "\nKilling Session...."
		/sbin/fuser -k -9 /dev/${t_a[i]} 1>/dev/null 2>&1
		printf "  Done!\n"
		;;
	    (*)printf "NOT confirmed - No action taken\n" exit ;;
	esac
}

# Function to list a list of sessions showing marks, if any
listSessions() {
	if [ $SessionsCount -eq 0 ]
	    then
		printf "No sessions found!\n"
		exit
	fi
	printf "\n\n                   List of sessions (%d found)\n" $SessionsCount
	printf "______________________________________________________________________________\n"
	printf " Session No   USER     TTY      IDLE     LOGIN@ FROM\n"
	printf "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"
	typeset -i i=0 SessionCount
	while [ $i -lt $SessionsCount ]
	  do
	  printf " %5d        %-8.12s %-8.12s %-8.12s %-6.12s %-16.128s\n" \
	      $i  "${u_a[i]}" "${t_a[i]}" "${i_a[i]}" "${l_a[i]}" "${f_a[i]}"
	  i=i+1
	done
	printf "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"
}

#
# Function to get the sessions and store them in an arry
#

getSessions() {
	printf "\nCollecting login information...."
	typeset -i i=0 
	/usr/bin/w -f > ${LOC_FILE}

	{
		read uptime_details
		read column_headers
		while read u_a[$i] t_a[$i] f_a[$i] l_a[$i] i_a[$i] j_a[$i] p_a[$i] c_a[$i]
		    do
			i=i+1
		done 
	} < ${LOC_FILE}

	SessionsCount=$i
}

# main starts here (keep bugging the user until s/he decides to quit)

while :
    do
	getSessions
	listSessions
	printf "\nEnter Session Number to terminate (q to quit) "
	read choice
	case $choice in
	    (Q|q) exit ;;
	    (""|*[!0-9]*) printf "Please enter a number\n" >&2 ;;
	    (*)
	    if [ $choice -lt 0 -o $choice -ge $SessionsCount ]
		then
		    printf "Please enter a value between 0 and $((SessionCount-1))\n"
	    else
		    killSession $choice
	    fi
	esac
done # main while
