#!/usr/bin/perl

###########################################################
#
# Licensed Material - Property of IBM
#
# bogosec_wrapper 
#
# (C) Copyright IBM Corp. 2004-2008
#
# Description - script that will go through a directory and run bogosec on
#		all the files in it. Output is then saved in a temp result file.
# HISTORY -
#       01/05 Author - Loulwa Salem (loulwa@us.ibm.com)
#	02/05 Loulwa Salem (loulwa@us.ibm.com) - replaced shell commands with Perl code
#	03/05 Loulwa Salem (loulwa@us.ibm.com) - added code to accept command options for bogosec
###########################################################

# globals and default values
my %OPTS = (
		temp_dir	=>	"/tmp/"
);

my $target = $ARGV[0];
my $cmd_options = $ARGV[1];
my $result_file = mkstemp($OPTS{temp_dir} . "bogosec.results.XXXXXX");
my $bogosec_output = mkstemp($OPTS{temp_dir} . "bogosec.detail_results.XXXXXX");
my $bogosec_raw_output = mkstemp($OPTS{temp_dir} . "bogosec.raw.XXXXXX");
my $new_target = "";
my @list = ();

if (! -d $target) {
	print "\n\tUsage: bogosec_wrapper TARGET_DIRECTORY \"OPTIONS\"\n";
	print "\n\tThe target you provided is not a directory\n";
	print "\tFor additional information, please refer to bogosec_wrapper manpage\n\n";
}

# Initial preparation of the needed files
open(FH, ">$result_file") || die "Cannot open $result_file \n";
open(TEMPFH, ">$bogosec_output") || die "Cannot open $bogosec_output \n";
print FH ("START : " . `date`);
print FH "======================================\n";
print FH "Package\t\t\t\t\t Sev Points\tLines Of Code\tFinal Score\n";

# open the target directory and obtain a list of its files. 
#	Eliminate the . and .. listings (Not needed and causes problems in some cases).
opendir(DH, $target);
while (my $entry  = readdir(DH)) {
	if ($entry =~/^[\.]{1,2}$/) {
		next;
	}
	else {
		push (@list, $entry);
	}
}

foreach $src_list(@list) {
	chomp($src_list);
# if target directory doesn't end in a "/", add one, then run bogosec on it
	if ( ($target =~ /.\/$/) ) {
		$new_target = $target . $src_list;
	} else {
		$new_target = $target . "/" . $src_list;
	}
	`bogosec $cmd_options $new_target > $bogosec_raw_output`;
# Format bogosec output and print it in column like format
	my ($temp1, $sev_pts) = split(/\s+/,`grep "severity points" $bogosec_raw_output`);
	my ($temp1, $LOC) = split(/\s+/,`grep "lines of code" $bogosec_raw_output`);
	my ($temp1, $temp1, $temp1, $temp1, $score) = split(/\s+/,`grep "final score" $bogosec_raw_output`);

	printf FH ("%-40s %-14d %-15d %.16g\n", $src_list,$sev_pts,$LOC,$score);
	print TEMPFH "TARGET : $new_target\n";
	print TEMPFH (`cat $bogosec_raw_output`);
	print TEMPFH "======================================\n";
}
closedir(DH);
close(FH);
close(TEMPFH);
unlink($bogosec_raw_output);
