#!/usr/bin/perl
#
#   Run the plugins which have been setup.
#
# Steve
# --
# http://www.steve.org.uk
#

use strict;
use Env;

#
#  The fixed settings we work with.
#
my $CONFIG     = "/etc/checksecurity.conf";
my $PLUGIN_DIR = "/usr/share/checksecurity";
my $VERSION    = "2.0.0";



# Copy of the environmental variables.
my %SAFE_ENV   = %ENV;

# Environmental settings we read from the configuration file.
my %GLOBAL_ENV = ();

# The environment that we send to the plugins we call.
my %PLUGIN_ENV = ();



#
# Source the configuration file.
#
if ( -e $CONFIG )
{
    %GLOBAL_ENV = readConfig( $CONFIG );
}
else
{
    print <<E_O_F;
  The global configuration file that checksecurity wishes to read
 in order to know which plugins are enabled is missing.

  Please see man 'checksecurity.conf' for details of the contents
 this file should have.

  Aborting.
E_O_F
}



#
# Look for plugins
#
foreach my $file (glob( $PLUGIN_DIR . "/check-*" ) )
{
    # Skip dotfiles.
    next if ( $file =~ /^\./ );

    my $name = "";

    if ( $file =~ /(.*)check-(.*)/ )
    {
	$name = $2;
    }

    $name = uc( $name );

    # See if the plugin is enabled.
    if ( $GLOBAL_ENV{ "CHECK_$name" } eq "TRUE" ) 
    {
	# Determine the configuration file this plugin wishes to use.
	$name = lc( $name );
	my $conf = "/etc/checksecurity/check-$name.conf";

	# Reset to the known good environment.
	%ENV  = %SAFE_ENV;


	if ( -e $conf )
	{
	    %PLUGIN_ENV= &readConfig( $conf );
	}
	else
	{
	    %PLUGIN_ENV = ();
	}

	# Setup the environment
	foreach my $k ( keys( %PLUGIN_ENV) )
	{
	    $ENV{$k} = $PLUGIN_ENV{$k};
	}

	# Execute the file.
	system( $file );
    }
    else
    {
	print "\tDisabled\n";
	#print "Value was " . $GLOBAL_ENV{ "CHECK_$name" } . "\n";
    }
}


#
#  Read a name=value configuration file, and return a hash containing
# each of values keys.
#
sub readConfig( $ )
{
    my ( $file ) = ( @_ );

    my %HASH;
    open( FILY, "<$file" ) or die "Cannot open file: $file - $!";

    my $line       = ""; 
    my $lineCount  = 0;

    while (defined($line = <FILY>) ) 
    {
        chomp $line;
	if ($line =~ s/\\$//) 
	{
	    $line .= <FILY>;
	    redo unless eof(FILY);
	}
      
	# Skip lines beginning with comments
	next if ( $line =~ /^([ \t]*)\#/ );

	# Skip blank lines
	next if ( length( $line ) < 1 );

	# Strip trailing comments.
	if ( $line =~ /(.*)\#(.*)/ )
	{
	    $line = $1;
	}

	# Find variable settings
	if ( $line =~ /([^=]+)=([^\n]+)/ )
	{
	    my $key = $1;
	    my $val = $2;

	    # Strip leading and trailing whitespace.
	    $key =~ s/^\s+//;
	    $key =~ s/\s+$//;
	    $val =~ s/^\s+//;
	    $val =~ s/\s+$//;
	    
	    # Strip enclosing "'s
	    if ( $val =~ /^['"](.*)['"]$/ )
	    {
		$val = $1;
	    }

	    # Store value.
	    $HASH{ $key } = $val;
	}
    }
    close(FILY);
    return(%HASH);
}
