#!/bin/sh

# ####################################################################
# Exceed Connection Server 13.7
# Copyright (c) 1997-2009 Open Text Corporation. All Rights Reserved.
# ####################################################################
# sessclean
# $Revision: 14851 $
# ####################################################################

# sessclean - clean up all proxy sessions

# some constants
PidFileName=mypid
Proxyname=ewebhost

#process command line
if [ "$1" = "-q" ] ; then
	Quiet=1
	SessionsRoot="$2"
else
	Quiet=0
	SessionsRoot="$1"
fi

if [ -z "$SessionsRoot" ] ; then
	exit 1
elif [ ! -d "$SessionsRoot" ] ; then
	exit 1
fi

# get list of sessions dir with a vaild pid file
Sessions=""
for dir in `ls $SessionsRoot`; do
	if [ -r "$SessionsRoot$dir/$PidFileName" ] ; then
		Sessions="$Sessions $dir"
	fi
done

if [ -z "$Sessions" ] ; then
	exit 1
fi

# terminate sessions
for dir in $Sessions; do
	if [ -r $SessionsRoot$dir/$PidFileName ] ; then
		read thispid < $SessionsRoot$dir/$PidFileName
		if ps -p "$thispid" 2> /dev/null | grep "$Proxyname" > /dev/null 2>&1 ; then
			kill "$thispid" > /dev/null 2>&1
		fi
	fi
done

Remaining=""
# cleanup sessions
for dir in $Sessions; do
	if [ -r $SessionsRoot$dir/$PidFileName ] ; then
		read thispid < $SessionsRoot$dir/$PidFileName
		if ps -p "$thispid" 2> /dev/null | grep "$Proxyname" > /dev/null 2>&1 ; then
			Remaining="$Remaining $dir"
		else
			rm -rf "$SessionsRoot$dir" > /dev/null 2>&1
		fi
	fi
done

if [ -z "$Remaining" ] ; then
	exit 1
fi

# kill sessions
sleep 1
for dir in $Sessions; do
	if [ -r $SessionsRoot$dir/$PidFileName ] ; then
		read thispid < $SessionsRoot$dir/$PidFileName
		if ps -p "$thispid" 2> /dev/null | grep "$Proxyname" > /dev/null 2>&1 ; then
			kill -9 "$thispid" > /dev/null 2>&1
		fi
		# remove the dir
		rm -rf "$SessionsRoot$dir" > /dev/null 2>&1
	fi
done
