#!/usr/local/bin/perl -s

# Copyright (c) 2004-2007, The PalCom Project consortium.
# See http://www.ist-palcom.org/consortium.
# 
# All rights reserved.
# 
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
# 
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
# 
#     * Redistributions in binary form must reproduce the above
#       copyright notice, this list of conditions and the following
#       disclaimer in the documentation and/or other materials provided
#       with the distribution.
# 
#     * Neither the name of the PalCom Project nor the names of its
#       contributors may be used to endorse or promote products derived
#       from this software without specific prior written permission.
# 
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


# 
# Prepends palcom copyright notice to argument file
# attempting to check if it is already there.
# 
# Suggested use is with the find command:
#   find <dir> -name '*.java' -exec pal-dev-add-copyright -v '{}' \;
# or more general
#   find <dir> \( -name '*.java' -o -name '*.cpp' -o ... \) -exec pal-dev-add-copyright -v '{}' \;
#
# See also pal-dev-add-copyrights-all
#
# BE CAREFULL not to add PalCom copyright to included third-party files!
# The script attempts to identify such copyright "thefts" but it is not
# bulletproof!
#

# output level:
#   0: quiet - only errors
#   1: normal - only changed files (default)
#   2: verbose - status of each file

$outputlevel = 1; # default
$outputlevel = 2 if ($v);
$outputlevel = 0 if ($q);

$longformat = 1 if ($l);
$delete = 1 if ($d);

usage() if ($h);
usage() if ($#ARGV!=0);
$file = $ARGV[0];

if ( ! -f $file){
    report("?", "Not a regular file", 0);
    exit;
}

# Check for existence of .othercopyright file in same dir
if ($file =~ m%/%){
    $othercopyright = $file;
} else {
    $othercopyright = "./$file";
}
# $othercopyrightthisfile: .../file -> .../.othercopyright-file
$othercopyrightthisfile = $othercopyright;
$othercopyrightthisfile =~ s%/([^/]+)$%/.othercopyright-$1%;
# $othercopyright: .../file -> .../.othercopyright
$othercopyright =~ s%/[^/]+$%%;
$othercopyright .= "/.othercopyright";
$othercopyright = ( -f $othercopyright || -f $othercopyrightthisfile );

if ( $file =~ /(~$|\.(jpg|gif|pdf|exe|jar|png|bmp|ps|eps|log|lox|aux|dvi|bbl|blg|out|log|othercopyright.*)$)/i){
    report("i", "Ignored file type", 2);
    exit;
} elsif ( $file =~ /\.svn/){
    report("i", "Ignored SVN file", 2);
    exit;
} elsif ( $file =~ /\.(java|c|cpp|h|hpp|jrag|jadd|ast|g)$/){
    $multiline=1;
    $begin = "/*";
    $end   = "*/";
} elsif ( $file =~ /\.(html)$/){
    $multiline=1;
    $begin = "<!--";
    $end   = "-->";
    # Leave first line if it is a DOCTYPE
    $firstlines = read_first_lines($file, 3);
    $firstlines = "" unless ($firstlines =~ /DOCTYPE/);
} elsif ( $file =~ /\.(st)$/){
    $multiline=1;
    $begin = "\"";
    $end   = "\"";
} elsif ( $file =~ /\.(bat)$/){
    $begin = "::";
} elsif ( $file =~ /\.(tex|sty|bib)$/){
    $begin = "%";
} elsif ( $file =~ /\.(pl|sh)$/){
    $begin = "#";
    $firstlines = read_first_lines($file, 1);
} elsif ( $file =~ /(Makefile|GNUmakefile|makefile|\.pcs|Component)$/ ){
    # Currently fails for pcs files compiled by pal-j
    $begin = "#";
} elsif ( ($firstlines = read_first_lines($file, 1)) =~ /^\#!/ ){
    # shell/perl script
    $begin = "#";
} elsif ( $othercopyright ){
    # Unknown file in 3rdparty directory.
    # We let it fall through to perform test for illegal
    # PalCom copyright manually added
} else {
    report("?", "Unsupported file type", 0);
    exit;
}
	  
# Read target file
$lines = read_file($file);

# Identify and remove possibly existing PalCom copyright comment
if ($multiline){
    if ($lines =~ s%\s*(\Q$begin\E\s*Copyright \(c\) 2004.+The PalCom Project.+?\Q$end\E)\s*%%s){
	$oldnotice = $1;
    }
} else {
    if ($lines =~ s%(\Q$begin\E\s*Copyright \(c\) 2004.+The PalCom Project.+SUCH DAMAGE\.)\s*%%s){
	$oldnotice = $1;
    }
}

# What kind of action needed?
if ($delete){
    report("d", "PalCom copyright deleted", 1) if ($oldnotice ne "");
} elsif ($othercopyright){
    if ($oldnotice ne ""){
	report("*", "*** WARNING: PalCom copyright in 3rd party directory!", 0);
    } else {
	report("3", "Third party directory; file ignored", 2);
    }
    exit;
} else {    
    # New copyright notice
    $license=read_license_file();	  
    if ($multiline){
	$notice = "$begin$license$end";
    } else {
	# remove initial and trailing whitespace from read license file
	$license =~ s/^\s*//; 
	$license =~ s/\s*$//; 
	$notice = $license;
    }
    #print "'$oldnotice'\n";
    #print "'$notice'\n";
    if ($notice eq $oldnotice){
	report("-", "No change", 2);
	exit;
    }
    if ($oldnotice eq "" && ($lines =~ /copyright/i)){
	report("!", "*** Potential other Copyright found - ignoring file", 0);
	exit;
    }
    # Add copyright notice
    $lines = "$notice\n\n$lines";
    $lines = "$firstlines\n$lines" if ($firstlines);
    if ($oldnotice ne ""){
	report("u", "PalCom copyright updated", 1);
    } else {
	report("a", "PalCom copyright added", 1);
    }
}

# Write updated file;
if (!open(OUT, ">$file")){
    print STDERR "***Cannot open $file for writing: $!\n";
    exit 1;
}
print OUT $lines;
close OUT;

exit;

sub usage($msg)
{
    my $msg = shift;
    print "\n$msg\n" if ($msg);
    print "Usage: pal-dev-add-copyright [-h] [-v] [-q] [-l] [-d] <file>\n";
    print "  <file> may be a C/C++, Java, JastAdd, AntLR, TeX, BAT, SH, Perl,\n";
    print "  PalCom Component Specification file, or (GNU)Makefile.\n";
    print "  Options:\n";
    print "    -h  help: print this help\n";
    print "    -d  delete: delete existing palcom copyright without adding a new\n";
    print "    -v  verbose: say for each file what is done\n";
    print "    -q  quiet: only list changed files and problems\n";
    print "    -l  long format: display explanatory text instead of one letter indicators\n";
    print "\n";
    print "  Action indicators (if -l not specified):\n";
    print "    a copyright added\n";
    print "    u copyright updated\n";
    print "    d copyright deleted\n";
    print "    - file untouched\n";
    print "    ! other copyright detected; file untouched\n";
    print "    3 file in 3rdparty directory (.othercopyright file); file untouched\n";
    print "    * PalCom copyright found in 3rdparty file(!); file untouched\n";
    print "    i known file to ignore; file untouched\n";
    print "    ? unsupport file type; file untouched\n";
    exit;
}

sub report($short, $msg, $level)
{
    my ($short, $msg, $level) = @_;
    if ($outputlevel >= $level){
	if ($longformat){
	    print "$file\n  $msg\n";
	} else {
	    print "$short $file\n";
	}
    }
}

sub read_first_lines($file)
{
    my $filename = shift;
    my $numlines = shift;
    my $line = "";
    if (!open(IN, "$filename")){
	print STDERR "***Cannot open $filename for reading: $!\n";
	exit 1;
    }
    $firstlines_read = $numlines;
    $line .= <IN> while ($numlines-- > 0);
    close (IN);
    return ($line);
}

sub read_file
{
    my $filename = shift;
    my $lines = "";
    if (!open(IN, "$filename")){
	print STDERR "***Cannot open $filename for reading: $!\n";
	exit 1;
    }
    if ($firstlines){
	# first lines already read
	$skip = <IN> while ($firstlines_read-- > 0); 
    }
    while (<IN>) {
	$lines .= $_;
    };
    close (IN);
    return ($lines);
}

sub read_license_file
{
    my $root=`pal-dev-root`;
    chomp $root;
    my $lines="\xa"; # start with a newline
    if (!open(IN, "$root/LICENSE.txt")){
	print STDERR "***Cannot open $root/LICENSE.txt: $!\n";
	exit 1;
    }
    while (<IN>) {
	my $line = $_;
	$line   =~ s/\xa$//; # remove possible linefeed
	$line   =~ s/\xd$//; # remove possible carriage return
	if (!$multiline){
	    $line =~ s/^   /$begin /; # add comment-begin to each indented line
	    $line =~ s/^$/$begin /;   # add comment-begin to each empty line
	}
	$line  .= "\xa"; # apply unix newlines 
	$lines .= $line;
    };
    close (IN);
    return ($lines);    
}

