#!perl -w
# $Id: copyright.pl,v 1.3 2004/09/30 07:34:13 jlinoff Exp $
#
# This perl script replaces the copyright notice in all source code
# with copyright data from a file specified specified on the command
# line.
#
# The copyright notice must be bounded by the following comments:
# //@copyright_begin
# //@copyright_end
#
use strict;
&Main;

# ================================================
# Main
# ================================================
sub Main {
  my $verbose = 0;
  my $copyright_file = "";
  my @files = ();
  while ( $#ARGV >= 0 ) {
    my $arg = shift @ARGV;
    if( $arg eq "-c" ) {
      $arg = shift @ARGV;
      $copyright_file = $arg;
    }
    elsif( $arg eq "-h" || $arg eq "-help" ) {
      &Usage;
    }
    elsif( $arg eq "-v" ) {
      $verbose = 1;
    }
    else {
      push @files,$arg;
    }
  }

  my $file;
  foreach $file ( @files ) {
    &Process($copyright_file,$file,$verbose);
  }
}
# ================================================
# Process
# ================================================
sub Process {
  my $copyright_file = shift;
  my $file = shift;
  my $verbose = shift;

  print "processing $file ...\n" if( $verbose );

  if( ! -w $file ) {
    print STDERR "ERROR: File '$file' is not writeable.\n";
    return;
  }
  if( ! -r $copyright_file ) {
    print STDERR "ERROR: Copyright file '$file' is not readable.\n";
    return;
  }

  open IFP,"$file" || die "ERROR: Can't read '$file'.\n";
  open OFP,">$file.tmp" || die "ERROR: Can't read '$file.tmp'.\n";
  while( <IFP> ) {
    chop;
    my $line = $_;
    if( $line =~ /\/\/\@copyright_begin\s*$/ ) {
      print OFP "//\@copyright_begin\n";
      print OFP "// ================================================================\n";
      print OFP "// Copyright Notice\n";
      open CFP,"$copyright_file" || die "ERROR: Can't read '$copyright_file'.\n";
      while( <CFP> ) {
	print OFP "// $_";
      }
      close CFP;
      print OFP "// ================================================================\n";
      print OFP "//\@copyright_end\n";
      while( <IFP> ) {
	chop;
	$line = $_;
	last if( $line =~ /\/\/\@copyright_end\s*$/ );
      }
    }
    else {
      print OFP "$line\n";
    }
  }
  close OFP;
  close IFP;
  rename "$file.tmp","$file";
}
# ================================================
# Usage
# ================================================
sub Usage {
  my $X = "\$";
  print <<END

\$Id: copyright.pl,v 1.3 2004/09/30 07:34:13 jlinoff Exp $X

usage: perl copyright.pl [-c <file>] [-h] [-help] <files>

  -c <file>  The name of the file containing the copyright text.

  -h,-help   This help message.

  -v         Verbose mode. Report each file that is being processed.

  <files>    The files to substitute.

example:

  % perl copyright.pl -c copyright.txt *.c *.h

END
}

