#!/usr/bin/perl

###############################################################################
#
# fixperl.pl
#
# AUTHOR:	Shawn Stepper, wiTHinc Inc.
# AUTHOR:	George Toye, wiTHinc Inc.
# DATE:		$Date: 2001/08/21 17:50:53 $ (last modified)
# COPYRIGHT:	1998, 1999, 2000, 2001 wiTHinc Inc. All Rights Reserved.
#
###############################################################################

# This program changes the specification for the location of perl in
# perl scripts specified in the file specified on the command line

$listfile = @ARGV[0];
$args = @ARGV;
$perlloc = @ARGV[$args - 1];

if (@ARGV < 2 || ! -e $listfile || @ARGV[$args - 1] !~ /perl/i) {
	print "Usage: perl $0 <listfile | file_to_modify> file_to_modify... perl_location\n";
	print "	(Hint: the file you specify must exist, and the last argument ";
	print "must have\n	 the word 'perl' in it somewhere.)\n";
	exit(1);
}

print "Changing perl location to $perlloc\n";

if ($perlloc !~ /\#\!/) {
	$perlloc = "#!" . $perlloc;
}

# Add files specified to the list
for ($i=0; $i < $args - 1; $i++) {
	$listfile = @ARGV[$i];
	if (!open(f, $listfile) ) {
		print "Error: Cannot open $listfile for reading\n";
		exit(1);
	}
	@flist = <f>;
	close(f);

	if (@flist[0] =~ /^\#/ && @flist[0] =~ /perl/i) {
		# The file specified is not a listfile, but a perl program.
		push(@filelist, $listfile);
	} else {
		# This file may contain a list of files to modify
		chomp(@flist);
		push(@filelist, @flist);
	}
	
	splice(@flist,0);
}

# Now go through each file in the list, and make sure it is a perl program and
# is writable

for ($i=0; $i < @filelist; $i++) {
	$listfile = @filelist[$i];
	
	if (! -e $listfile) {
		print "Error: $listfile does not exist. Skipping.\n";
		next;
	}
	if (! -r $listfile) {
		print "Error: Cannot open $listfile for reading. Skipping.\n";
		next;
	}
	
	open(f, $listfile);
	@flist = <f>;
	close(f);
	
	if (@flist[0] =~ /^\#/ && @flist[0] =~ /perl/i && -w $listfile) {
		# The file specified is not a listfile, but a perl program.
		print "Modifying file: $listfile\n";
		@flist[0] = $perlloc . "\n";
		open (f, ">$listfile");
		print f @flist;
		close(f);
	} elsif (! -w $listfile) {
		# Don't have write permission
		print "Error: Don't have write permission to $listfile. Skipping.\n";
	} else {
		# This is not a perl file
		print "Error: $listfile is not a perl file. Skipping.\n";
	}
	
	splice(@flist,0);
}

# print "Finished!\n";

exit(0);
