#!/bin/csh
#   Given a specific drive, blink it's activity and fail leds.
#
#   For now, the activity led is blinked by dd'ing data off the 
#   drive... not great, but works. The fail led is controlled
#   using the drive_fail_led tool.
#

# catch the INTR (interrupt) signal so that we can make sure we
# turn off the drive "fail" LED when we are killed
onintr	cleanup

if ( $# != 1 || "X$1" == "X-h" ) then
    if ( $# > 1 ) then
	echo "Starting separate processes to blink each drive."
	echo "Unfortunately, you'll have to kill them yourself."
	foreach disk ( $* )
	    $0 $disk &
	end
	wait
	## Unfortunately I can't get "onintr" to work with that wait...
	## so you have to kill all kids yourself.
    else
	echo "Please specify a drive to blink (any isi_drivenum-style arg ok)"
    endif
    exit
endif

set DRIVE = `isi_drivenum -t -- $1`
if ( $status != 0 ) then
    echo "Failed to recognize '$1' as a drive."
    echo "Please specify a drive to blink (any isi_drivenum-style arg ok)"
    exit
endif

set BAY   = `isi_drivenum -b -- $1`

echo "Blinking bay $BAY using $DRIVE..."

# tool to control drive fail led
set FAIL = /usr/bin/isi_hwtools/drive_fail_led

# start with fail led off (normally it will be, but just to be sure...)
$FAIL -b $BAY -s 0

set LOOPPID = $$

while (1)
	# turn the activity and fail leds on for one second

	# First line turns the drive fail led on.
	# Second line starts a dd that'll last longer than one second.
	# Third line guarantees that if that dd fails, we stop the loop
	#   The dd is expected to fail when we yank the drive, and we
	#   expect this blink script to be used to help find which drive 
	#   to yank.
	# Fouth line kills the dd and turn the fail led off after one 
	#  second, to set our on-time to one second
	# Fifth line backgrounds this whole dd/kill combo so that if
	#   we ctrl-C this script, we still kill the dd and turn the fail
	#   led off after a second.
	# Final line shuts up the output of the pid on backgrounding
	( ( ( $FAIL -b $BAY -s 1 ) ;				\
	    ( dd if=$DRIVE of=/dev/null bs=1m count=1000	\
	        || kill $LOOPPID) & ;				\
	     sleep 1 ; ( $FAIL -b $BAY -s 0 ) ; kill %1 ; ) 	\
	   & )							\
	  >& /dev/null

	# The above is backgrounded, so takes no time... 
	# we want it on for one second, then off for one... so that's
	# two seconds total before restarting.
	sleep 2
end

# don't leave without making sure the drive "fail" led is off
cleanup:
$FAIL -b $BAY -s 0

