#!/bin/csh

#set noglob
####################################################################################
#
#
#          This script does the pattern replace for all the files under the
#          directory given by command line argument. The patterns are defined
#          in sed_pattern_file.
#
#
####################################################################################

if( $#argv == 0 ) then
        echo "USAGE: searchandreplace <directory_name> "
	exit 1
else
        set dir = $argv[1]
	echo "Starting searchandreplace on $dir"
endif
echo $dir
if( ! -d $dir ) then
        echo $0\: $dir not a directory
        exit 1
endif

set cust_file = Customize.java

if( ! -f $cust_file ) then
	echo $cust_file not found
	exit 1;
else
	javac Customize.java
endif

# For Each file under the directory
# Check the type of file, If it is ordinary file then
# Do a Pattern replace using SED else
# If it is a directory then walk through directory recursively doing
# the same pattern replace
foreach file ($dir/*)
        if( ! -d $file ) then
		# Don't try to run sed on binary files: we skip 
		# according to suffix
		set suffix = $file:e
		set base = $file:r

		set excludes = "zip jar class o so dll gif pdf clz isj"
		set skip_flag = 0
		if ($file != $file:r) then
		    foreach f ($excludes)
			if ($suffix == $f) then
			    set skip_flag = 1 
			endif
		    end
		endif 

		if ($skip_flag == 1) then
		    echo "skipping substitution for file $file"
		else
		    set permset = 0
                    echo "Dealing with file => $file"
                    java Customize $file 
		    sed -f sed_pattern_file.version $file > $file.123456
		    if( ! -z $file.123456 ) then

			    if( ! -w $file ) then
				    chmod +w $file
				    set permset = 1
			    endif

			    \mv -f $file.123456 $file

			    if ( $permset == 1 ) then
				    set permset = 0
				    chmod -w $file
			    endif
			    
		    else
			    \rm -f $file.123456
		    endif
		endif
        else
		#Recursively Walk through the directory structure
		# and replace the pattern strings (i.e Package names)		
       		/bin/csh searchandreplace $file  
        endif
end

