#!/bin/sh

# Start/stop/restart an opensm session
#

# Copyright C 2002-2003 by Isilon Systems, Inc. All rights not expressly
# granted herein are reserved.
# Created in the United States of America.
# 
# This digital media is protected by U.S. and international copyright and
# intellectual property laws. Unless otherwise specified, all information
# and screens appearing as part of this digital medium, including
# software, services, documents, text, images, icons, and logos design;
# the selection, assembly, arrangement, and design thereof; and the code
# that enables its presentation, are the sole property of Isilon Systems,
# Inc.
# 
# Except as otherwise required by applicable law, no part of any
# copyrighted material may be reproduced, modified, translated,
# distributed, published, or transmitted by any means, electronic or
# mechanical, for any purpose, without the prior written consent of Isilon
# Systems. 
#  
# Isilon and Isilon Systems are registered trademarks of Isilon Systems,
# Inc.  Legion is a trademark of Isilon Systems, Inc.  All other
# trademarks and registered trademarks are the property of their
# respective holders.

# -P notes:  
#   There are actually two retries:
#   1) the polling one for when opensm is in standby.  This is the 3rd 
#      parameter to -P.
#   2) a low-level (vl15) retry which is hard-coded to 4 and applies
#      to all requests we initiate.  The period is set by -t.
#   4 * 1000 = 4000, so make the polling interval at least 4000.
ib_opensm_flags="-t 1000 -P 5000 5000 3"

# Set timeout duration for stopping
TIMEOUT=30
PIDFILE=/var/run/opensm-$1.pid
umask 002

if [ $# -lt 2 ]; then
	echo "$0 interface# {start|stop|restart}"
	return 1
fi

case $1 in
1|2)
	;;#nothing	
*)
	echo "$0: $1 is not a legal interface number"
	echo "$0 interface# {start|stop|restart}"
	return 1
esac

case $2 in
start)
	if [ -e ${PIDFILE} ] && kill -0 `cat ${PIDFILE}` 2>/dev/null; then
		# We could just let opensm see the other process and exit, but it's good to be told
		echo "Process `cat ${PIDFILE}` is already running on port $1"
		false
	else
		/usr/sbin/daemon -c /usr/libexec/opensm $ib_opensm_flags -u $1 \
		    -f /var/log/opensm-$1.log -T /var/log/opensm-$1.topo \
		    -x /etc/mcp/sys/opensm-${1}.xml \
		    $3 $4 $5 $6 $7 $8 $9 </dev/null >/dev/null 2>&1
	fi
	;;
stop)
	if [ -e ${PIDFILE} ]; then
		PID=`cat ${PIDFILE}`
		kill $PID
		COUNT=0
		while kill -0 $PID 2>/dev/null && test $COUNT -ne $TIMEOUT
		do 
			sleep 1
			COUNT=`expr $COUNT + 1` 
		done
		if test $COUNT -eq $TIMEOUT; then
			echo "$TIMEOUT second timeout waiting for process $PID to terminate"
			false
		else
			true
		fi
	else
		echo Warning: ${PIDFILE} not found
		# Do not consider this an error--allow restart to continue
		true
	fi
	;;
restart)
	if $0 $1 stop; then
		$0 $1 start $3 $4 $5 $6 $7 $8 $9
	fi
	;;
*)
	echo "$0 interface# {start|stop|restart}"
	;;
esac
