#!/bin/csh -f
#+
# fcs_change_lamp -- update FCS reference files to use a new lamp
#
# Purpose:
#	Modify all FCS reference files in the current directory with
#	the specified lamp to use the new lamp.  This is intended to
#	allow you to rapidly change all files referencing the "Cu1"
#	lamp to use the "Cu2" lamp instead, in case the "Cu1" lamp
#	burns out during a night.
#
# Usage:
#	fcs_change_lamp <old_lamp> <new_lamp>
# 
# Arguments:
#	old_lamp = lamp currently listed in FCS reference files
#	new_lamp = new lamp to list in FCS reference files
# 
# Output:
#	Matching reference files in the current FCS directory are
#	updated. 
# 
# Restrictions:
#	Must be run from the account that owns the FCS reference files.
# 
# Exit values:
#	 0 = normal completion
#	 1 = wrong number of arguments
#
# Example:
#
#-
# Modification history:
#	2003-Mar-02	GDW	Original version
#-----------------------------------------------------------------------

set buf = $0
set cmd = $buf:t
set usage = "Usage: $cmd old_lamp new_lamp"
set temp_file = ${cmd}.TEMP
set debug = 0
if ( $debug ) then
    printf "DEBUG MODE ENABLED\n"
    set command = echo
else
    set command = ""
endif

# verify args...
if ( $#argv != 2 ) then
  printf "$usage\n"
  exit 1
endif

# parse args...
if ( $#argv >= 1 ) then
    set old_lamp = $1
    shift
endif
if ( $#argv >= 1 ) then
    set new_lamp = $1
    shift
endif

# verify that FCSTRACK is stopped...
get_deimos_pid fcstrack > /dev/null
if ( $status == 0 && $debug == 0 ) then
    printf "ERROR -- you must stop FCSTRACK before running this script.\n"
    exit 1
endif

# determine which files to manipulate...
set fcsdir = `show -s deifcs -terse outdir`
set files = ( `find $fcsdir -name '*.ref' -print` )
if ( $#files < 1 ) then
    printf "ERROR -- no reference files found in FCS dir $fcsdir\n"
    exit 1
endif

# loop over files...
@ n=0
foreach file ( $files )
    awk "NR==8 && /"$old_lamp"/{exit 1}" $file
    if ( $status ) then
	@ n++
	printf "Changing file $file..."
	awk 'NR==8{print "'$new_lamp'";next}{print}' $file >! $temp_file
	set backup_file = $file.old
	@ i=0
	while ( -e $backup_file )
	    @ i++
	    set backup_file = $file.old.$i
	end
	$command /bin/mv $file $backup_file
	$command /bin/mv $temp_file $file
	printf "done.\n"
   endif
end

if ( $n < 1 ) then
    printf "ERROR -- no files used the $old_lamp lamp -- nothing changed\n"
    exit 1
else
    printf "Changed $n files -- you should restart the FCSTRACK script.\n"
endif
exit