#!/bin/sh

#=============================================================================
#
# Id      : 
# Package : 
# File    : bb_start
# Author  : Tom Aeby
# Date    : 13/02/97
#
#
# Usage : $prog [start|restart|stop]
#
# Function :
#
#	Start/restart/stop big sister
#
# Notes :
#
# chkconfig: 2345 98 99
# description: Big Sister System and Network Monitor
#
#=============================================================================


##########
#
# The first argument tells what to do.
##########

umask 022
PATH="/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin"
state=$1
uxmon_asroot=no
bsuser=bs
bs_instdir=/l/lib/bs
bsdir=$bs_instdir
[ -d $bsdir/adm ] || bsdir=`csh -c "echo ~$bsuser"`
[ -d $bsdir/adm ] || bsdir=/usr/local/lib/bs

if [ -f $bsdir/adm/uxmon-asroot ]; then
    uxmon_asroot=yes
fi

now_user=`id | sed 's/^[^(]*(//' | sed 's/).*//'`
prefix="su - $bsuser"
[ "$now_user" = "$bsuser" ] && prefix=sh


killproc() {		# kill the named process(es)
	msg=${3-stopped}
	pid=`( \
		(ps cax 2>/dev/null| grep -w "$1" 2>/dev/null) || \
		(ps -e -o pid,comm,args 2>/dev/null | grep -w perl 2>/dev/null| grep -w $1 2>/dev/null) || \
		(ps -e -o pid,comm,args 2>/dev/null | grep perl | grep $1 ) || \
		(ps -e 2>/dev/null | grep $1 ) \
		) | \
	      grep -v "PID" | \
	      grep -v "grep" | \
	      awk '{print $1}'`
	[ "$pid" != "" ] && kill $2 $pid && echo $1 $msg 
}


start() {
	if [ -f $bsdir/bin/bsmon -a -f $bsdir/etc/bsmon.cfg ]; then
	    $prefix -c "$bsdir/bin/bsmon" > /dev/null 2>&1
	fi
	if [ -f $bsdir/bin/bbd -a -f $bsdir/adm/bb-display.cfg ]; then
	    $prefix -c "$bsdir/bin/bbd -b $bsdir"
	fi
	for f in $bsdir/adm/uxmon-net*; do
	    set `basename $f`
	    case $1 in
		*bak|*%)
		    continue
		    ;;
		*)
		    if [ x$uxmon_asroot = xno ]; then
			$prefix -c "$bsdir/uxmon/uxmon -r $bsdir/uxmon/uxmon-rules.pl -b $bsdir -c $1"
		    else
			$bsdir/uxmon/uxmon -r $bsdir/uxmon/uxmon-rules.pl -b $bsdir -c $1
		    fi
		    ;;
	    esac
	done
	if [ -f $bsdir/adm/bstrapd.cfg ]; then
	    # bstrapd will only run as root
	    $bsdir/bin/bstrapd
	fi
	echo "Big Sister started"
}


[ -d $bsdir ] || exit 0

case $state in

'start')
	( killproc uxmon -0 "still running" || \
	killproc bbd -0 "still running" || \
	killproc bb_event_generator -0 "still running" || \
	killproc bsmon -0 "still running" || \
	killproc bb_event_genera -0 "still running" ||
	killproc bstrapd -0 "still running" ) && \
	echo "WARNING: some Big Sister components are already running" >&2
	start
	;;
'stop')
	killproc uxmon -QUIT
	killproc bbd -QUIT 
	killproc bb_event_generator -QUIT
	killproc bsmon -QUIT
	killproc bb_event_genera -QUIT
	killproc bstrapd -QUIT
	;;
'restart')
	killproc uxmon -QUIT 
	killproc bbd -QUIT 
	killproc bb_event_generator -QUIT
	killproc bsmon -QUIT
	killproc bb_event_genera -QUIT
	killproc bstrapd -QUIT
	start
	;;
esac


