#!/usr/local/bin/perl

#
# A program to add the copyright on the gated (well, any) source file
# By default, C comment are used (/* ... */) to wrap the copyright,
# but that can be changed by the -w flag. The copyright is ended
# by the line "__END_OF_COPYRIGH__"
#

$copyrightFile = 'copyright';
$saveExt = 'bak';
$prefix = ' *';
$Ccomments = 1;
$TempDst = '.COPYRIGHT';
$EndOfCopyright = '__END_OF_COPYRIGHT__';
$LastLine = "This copyright has ben automaticly added by the util/addcopyright.pl program.\n$EndOfCopyright";

$usage = "Usage: $0 [-c CopyrightFile] [-w Delimiter] files [Files...]
	-c CopyrightFile: CopyrightFile contains the copyright.
	-w Delimiter: Delimiter is the prefix before any text. C comments
		are the default.
";

while($_ = $ARGV[0], /^-/) {
	shift;
	/^-c/ && do { $copyrightFile = $ARGV[0]; shift; next; };
	/^-w/ && do { $prefix = $ARGV[0]; shift; $Ccomments = 0; next; };
	/^-/  && do { die $usage; };
}
die $usage if (!$ARGV[0]);

#
# Go through al arguments
#
for(; $ARGV[0]; shift) {

	$src = $ARGV[0];
	print "Processing \"$src\"\n";

	# Open the  source file, and the dst file...

	open(SRC, $src) || do {
		print "Cannot open \"$src\": $!; skipping...\n";
		next;
	};
	open(DST, ">$TempDst") ||
		die("Cannot open temporary file \"$TempDst\": $!");

	# Write the copyright file to the temp file

	open(CPR, $copyrightFile) ||
		die("Cannot open copyright file \"$copyrightFile\": $!");

	print DST "/*\n" if ($Ccomments);
	while(<CPR>) {
		# Get rid of any wierd stuff...
		$_ =~ s/^[ \t\*#%]*//;

		print DST "$prefix $_";
	};

	# Print the end of copright stuff...

	$eocpr = $LastLine;
	$eocpr =~ s/\n/\n$prefix /g;
	print DST "$prefix $eocpr\n";

	# Copy the source file. See if a copyright was already there

	open(BAK, ">$src.$saveExt") ||
		die("Cannot open backup file \"$src.$saveExt\": $!");
	while(<SRC>) {
		/$EndOfCopyright/ && ($cprThere = 1);

		print BAK $_;
	}
	close(BAK);
	close(SRC);

	# If a copyright was already there we do not need to close the
	# C comments.
	print DST " */\n" if ($Ccomments && !$cprThere);
	print DST "\n" if (!$cprThere);

	open(SRC, $src) ||
		die("Cannot reopen source file \"$src\": $!");

	# Now print the rest of the source file to the DST file

	while(<SRC>) {
		/$EndOfCopyright/ && do { $cprThere = 0; next; };
		$cprThere && next;

		print DST $_;
	};
	close DST;
	close SRC;

	# Remane

	rename($TempDst, $src) ||
		die("Cannot rename \"$TempDst\" to \"$src\": $!\n");
}




