#!/bin/bash

. /usr/lib/pm-utils/functions

get_pipes () {
	pipes=""
	FILES=`find /tmp -name "stp.*" 2>/dev/null`
	for file in ${FILES}
	do
#		echo "file is ${file}"
		#get string after "/tmp/stp."
		pid=${file#/tmp/stp[.]}
#		echo "pid is ${pid}"
		#run ps command without header and getting command name only
		psout=`ps ch ${pid}`
		if [ $? -eq 0 ]; then
			#convert output to lower case
			psout=`echo ${psout} | tr 'A-Z' 'a-z'`
#			echo "psout is ${psout}"
			#check to see if string contains "sametime"
			if [[ "${psout}" =~ "sametime" ]]; then
				echo "${file} is for a sametime process"
				if [ -n ${pipes} ]; then
					pipes="${pipes} ${file}"
				else
					pipes=${file}
				fi
			fi
		fi
	done
	return ${result}
}

hibernate_sametime() {
	# Tell Sametime to shut down connections
	sentMsg=0
	get_pipes
	for pipe in ${pipes}
	do
		echo "powermanagement hibernate >${pipe}"
		echo "powermanagement hibernate" >${pipe}&
		sentMsg=1
	done
	if [ ${sentMsg} -eq 1 ]; then
		# Give time for links to disconnect or sleep processing may hang
		sleep 3
	fi
}

suspend_sametime() {
	# Tell Sametime to shut down connections
	sentMsg=0
	get_pipes
	for pipe in ${pipes}
	do
		echo "powermanagement suspend >${pipe}"
		echo "powermanagement suspend" >${pipe}&
		sentMsg=1
	done
	if [ ${sentMsg} -eq 1 ]; then
		# Give time for links to disconnect or sleep processing may hang
		sleep 3
	fi
}

resume_sametime() {
	# Tell Sametime it is being resumed
	get_pipes
	for pipe in ${pipes}
	do
		echo "powermanagement resume >${pipe}"
		echo "powermanagement resume" >${pipe}&
	done
}

thaw_sametime() {
	# Tell Sametime it is being resumed
	get_pipes
	for pipe in ${pipes}
	do
		echo "powermanagement thaw >${pipe}"
		echo "powermanagement thaw" >${pipe}&
	done
}

case "$1" in
	hibernate)
		hibernate_sametime
		;;
	suspend)
		suspend_sametime
		;;
	resume)
		resume_sametime
		;;
	thaw)
		thaw_sametime
		;;
	*)
		;;
esac

exit $?
