#!/usr/bin/perl
# g.pl
#
# Add a GPL compliant copyright notice to script files
# Currently only supports shell-style comments (# to EOL)
#
# The notice is added at the end of any initial comments to preserve
# shebang lines and program descriptions (such as this)
# 
# 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/>.

use strict;
use warnings;

my $notice =<<EOF;

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/>.
EOF

use Getopt::Long;
my $outfile;
my $comment = "#";
GetOptions ("output=s"  => \$outfile,
	    "comment=s" => \$comment);

die "Comment symbol must be one character ($comment given)\n"
	if length $comment != 1;

my $out;

if ($outfile) {
    open $out, "> $outfile" or die "Can't open $outfile: $!";
} else {
    open $out, ">-";
}

for (<>) {
    print $out quote($notice) if ?^[^#]?;
    print $out $_;
}

sub quote {
    my $quoted = shift;
    $quoted =~ s/^(.*)/$comment $1/mg;
    return $quoted;
}
