#!/bin/csh

### figure out what dir this program was found/run in (but if there
### was no path mentioned, don't just assume "./")
if ( "X$0" !~ */* ) then
    set rundir = "";
else
    set rundir = "`dirname $0`/"
endif
### and now figure out where to run diskscrub.  Might be in rundir
### or in rundir/diskscrub
if ( -f ${rundir}diskscrub) then
    set dsrundir = "${rundir}"
else
    set dsrundir = "${rundir}diskscrub/"
endif


set maxbay   = `isi_drivenum -Mb`
set slamlist = ""

while ($#)
    set linearg = $1;
    shift;

    switch ($linearg)
    case "-help":
    case "-h":
	echo "usage: $0 [-s] [disk | -a] [-x disk]..."
	echo "  Stops any slammer running on a bay not in list"
	echo "  and starts slammer on bay if in list."
	echo "  -s : show which bays are currently running slammers"
	echo "  -a : add all bays to list of slammers"
	echo "  -x B : remove given bay B from list (with -a)"
	echo "  otherwise adds to list"
	echo ""
	echo "  Egs:"
	echo "   $0                 turn off all running slammers"
	echo "   $0 -a -x 4 -x 5    slam all but bays 4 and 5"
	echo "   $0 1 2 6           run slammers on bays 1,2,6 (and no others)"
	exit;
	breaksw;
    case "-status":
    case "-s":
	set running = `ps -auxw | grep diskscrub | grep '\-5' | sed -e "s~.*\(/dev/[^ ]*\)~\1~"`
	if ( "X$running" == "X" ) then
	    echo "no slammers running"
	else
	    echo "slammer running on bays:   `isi_drivenum -b $running | sort`"
	endif
	exit;
	breaksw;
    case "-a":
	# add all bays to the slamlist
	set slamlist = "$slamlist `isi_drivenum -b`"
	breaksw;
    case "-x":
	set rmbay = `isi_drivenum -b $1` || \
	  echo "Unrecognized bay $1 -- exiting" && exit
	shift;
	set dollar = '$'
	set slamlist = "`echo $slamlist | tr ' ' '\012' | grep -v ^$rmbay$dollar`";
	breaksw;
    default:
	set addbay = `isi_drivenum -b $linearg` || \
	  echo "Unrecognized bay $linearg -- exiting" && exit
	set slamlist = "$slamlist $addbay"
	breaksw;
    endsw
end

if ("X$slamlist" == "X") then
    echo "stopping all slammers"
else
    set slamlist = `isi_drivenum -b $slamlist | sort | uniq`
    echo "setting slammers to run on bays $slamlist"
endif

@ BAY = 1
while ( $BAY <= $maxbay)
  set runslam = `echo $slamlist | tr ' ' '\012' | grep $BAY`
  set twed = `isi_drivenum -t $BAY`
  set slampid = `ps -auxw | grep diskscrub | grep '\-5' | grep $twed | awk '{ print $2 }'`

  if ( "X$runslam" == "X" ) then
    # don't want a slammer... kill it if it's running
    if ( "X$slampid" != "X" ) then
      kill $slampid
    endif
  else
    # want a slammer.  start it if it's not running
    if ( "X$slampid" == "X" ) then
      # extra parens to prevent showing the job-control process id
      ( ${dsrundir}diskscrub -5 $twed & )
    endif
  endif
  @ BAY = ($BAY + 1)
end
