#!perl
#use strict;
use File::Find;
use Getopt::Long;

sub findListofMakefiles
{
	my @allmkFiles = ();
	&File::Find::find( sub {push @allmkFiles, $File::Find::name if ($File::Find::name =~ /\.mk$/) 
		;}, "$ENV{'_TMROOT'}");
	return @allmkFiles;
}

sub checkTrailingSpaces 
{
	my @makefileList=@_;
	foreach my $makefile (sort @makefileList) {
		print "Checking $makefile for Trailing whitespaces\n";
	    open (MAKEFILE,$makefile) or 
                       die "Cannot open $makefile. $! ";
		while (<MAKEFILE>) {
			next if (/^\s*\#/);
			next if (/^\s*$/);
			if (/ \s+$/ ) {
				print "Found in Line number $. \n";
				print "$_\n" if ($verbose == 1);
			}
		}
		close MAKEFILE;
	}
}

sub ExistEnvironment
{
    my ($var) = @_;
    if( !exists $ENV {$var} )
    {
        print "Environment variable $var not defined\n";
        return 1;
    }
    return 0;
}

sub checkEnv
{
	my $errors = 0;
	$errors += ExistEnvironment('_TMROOT');
	exit 1 if ($errors > 0);
}

sub checkParameters
{
    GetOptions("f:s"   => \$mkfile,
			 "help!"   => \$help,
		     "v!"   => \$verbose,
		)
}

#
# Message about this program and how to use it
#
sub usage()
	{
		print STDERR << "EOF";

	usage: $0 [-h] [-v] [-f file]
		
	-h        : this (help) message
	-v        : verbose output
	-f file   : makefile

	example: $0 -v -f file (check file)
			 $0 -v (check all makefiles .mk in _TMROOT with verbose mode)
			 $0 (check all makefiles .mk in _TMROOT)

EOF
        exit;
    }


#
# Program Starts Here
###############################################################################
my @makefileList=();
checkEnv();
checkParameters(@ARGV);
usage() if (defined $help);
@makefileList=($mkfile) if ($mkfile);
@makefileList=findListofMakefiles() if (!$mkfile);
checkTrailingSpaces(@makefileList);
