#!/usr/bin/env perl

use File::Basename;
use File::Find;

# This script will attempt to add a license header at the top of all source
# files, unless it finds a comment already at the top of the source file

# make sure we're in the right directory
chdir(dirname($0));

# iterate over files in the source tree
find(\&addHeader, "./src");
sub addHeader {
    # check that the file is a java source file
    (-f and /\.java$/s) or return;
    my $file = $_;

    # open the file for reading
    open my $i, '<', $file or die "Can't read file: $!";
    
    # find the first non-whitespace line and ensure it is not already a header
    while (<$i>) {
        unless (/^\s*$/) {      # finds lines with only whitespace
            if (/^\/\*\*/) {    # finds lines with a comment header
                print "Found an existing header in '$file'\n";
                return;
            }
            print "Adding header to '$file'\n";
            last;
        }
    }

    # open a temporary file for writing
    open my $o, '>', "$file.HEADER_WORKING" or die "Can't write file: $!";

    # print the header to the new file
    print $o "/**\n *    $file";
    print $o '
 *    Copyright (C) 2010 New Zealand Digital Library, http://expeditee.org
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

';

    # rewind the source file
    seek $i, 0, 0;

    # copy the source file into the new file
    while (<$i>) {
        print $o $_;
    }

    close $o;
    close $i;

    # replace the file with the new file
    rename("$file.HEADER_WORKING", $file);
}
