#!/usr/bin/perl

use strict;
use warnings;


foreach my $file (@ARGV) {
    &check_file($file);
}


sub check_file {
    my $file = shift;
    open FILE, "<$file" or die "$file: $!";

    my $header;
    my $decl;
    my $gpl;
    my $bsd;
    my $mit;
    my $later = 0;
    while (<FILE>) {
	if (/FILE_LICENCE\s*\(\s*(\S+)\s*\)/) {
	    $decl = $1;
	} elsif (/the terms of the GNU General Public License(?: version (1|2))?/) {
	    $gpl = $1 ? $1 : 1;
	} elsif ($gpl && /version 2/) {
	    $gpl = 2;
	} elsif ($gpl && /version 3/) {
	    $gpl = 3;
	} elsif ($gpl && /any later version/) {
	    $later = 1;
	} elsif (/This software may be used, modified, copied, distributed, and sold/ ||
		 /Redistribution and use in source and binary forms, with or without/) {
	    $bsd = 1;
	} elsif (/Permission to use, copy, modify, and distribute this software for any/) {
	    $mit = 1;
	}
    }

    if ($decl) {
	if ($decl eq "GPL2_OR_LATER") {
	    if (defined $gpl) {
		if ($gpl != 2 || $later != 1) {
		    print "$file GPL2_OR_LATER disagrees with comment\n";
		}
	    } else {
		print "$file GPL2_OR_LATER but no comment\n";
	    }
	} elsif ($decl eq "GPL2_ONLY") {
	    if (defined $gpl) {
		if ($gpl != 2 || $later != 0) {
		    print "$file GPL2_ONLY disagrees with comment\n";
		}
	    } else {
		print "$file GPL2_ONLY but no comment\n";
	    }
	} elsif ($decl eq "GPL_ANY") {
	    if (defined $gpl) {
		if ($gpl != 1 || $later != 0) {
		    print "$file GPL_ANY disagrees with comment\n";
		}
	    } else {
		print "$file GPL2_ANY but no comment\n";
	    }
	} elsif ($decl eq "BSD2") {
	    if (!defined $bsd) {
		print "$file BSD2 but no comment\n";
	    }
	} elsif ($decl eq "BSD3") {
	    if (!defined $bsd) {
		print "$file BSD2 but no comment\n";
	    }
	} elsif ($decl eq "MIT") {
	    if (!defined $mit) {
		print "$file MIT but no comment\n";
	    }
	} elsif ($decl ne "PUBLIC_DOMAIN") {
	    die "$file Unexpected decl $decl\n";
	}
    } else {
	my $maybe = "";
	if ($gpl) {
	    $maybe = "possible GPL $gpl";
	    if ($later) {
		$maybe .= " or later";
	    } else {
		$maybe .= " only";
	    }
	} elsif ($bsd) {
	    $maybe = "possible BSD";
	} elsif ($mit) {
	    $maybe = "possible MIT";
	}
	print "$file no FILE_LICENCE declaration $maybe\n";
    }

    close FILE;
}
