#!/usr/bin/perl
#
#
# Add web interface to Big Sister notification schema
#
# Author: Brent Parish
# Date Created: 11/26/01
# Last update: 12/12/01 by BParish
#
# Dependancies:
#  You will need to add the # BEGIN GROUPS,  # BEGIN HOSTS, # END OF HOSTS comments in bb-display.cfg
#  If you are not using authentication on your site, delete the auth section
#  Change the auth users to valid ID's if you are using authentication
#  Set the path for BSHOME
#

use CGI qw/:standard *table *Tr/;
use IO::File;

print header();
print start_html(-title=>'bb_event_generator.cfg', -link=>'AQUA', -vlink=>'AQUA', -bgcolor=>'#111111', -text=>'WHITE');

### AUTH SECTION ###

# This username piece is here becuase we log into our system via apache authentication
$username = $ENV{'REMOTE_USER'};
if ($username ne "bparish" && $username ne "yzhou" && $username ne "gsherman") {
   print "<H1>Sorry!</H1>  <STRONG>You do not have access to this configuration tool!</STRONG>\n";
   exit;
}

### END AUTH SECTION ###

### SET THIS VARIABLE! ###

$BSPATH = "/home/bbuser";
  # NOTE THAT THIS IS AN ABSOLUTE PATH!

@sortme = ('*');
%rows = "";
$counter = 0;
@temparray = ();
$tempvar = "";
$FONT = '<FONT SIZE=-2 FACE=ARIAL COLOR="AQUA">';
@colnames = ('host','agent','time','check','router','prio','down','up','delay','repeat','repeatprio','norepeat','keep','mail','msgmax','pager','trap','postpone','postpone_to');

if (param('counter') > 0) {
  open(FILE,">${BSPATH}/adm/bb_event_generator.cfg") || die "Error -- Cant open config file for writing\n";
  $now = time;
  ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($now);
  if ($min < 10) {$min = "0$min";}
  if ($hour < 10) {$hour = "0$hour";}
  if ($mday < 10) {$mday = "0$mday";}
  $year = $year+1900;
  $comment = param('comment');
  $comment =~ s/\n/\n ## COMMENT:/g;
  print FILE " ## COMMENT:Last modified at $hour:$min $mday/$mon/$year by ".param('username')."\n";
  print FILE " ## COMMENT:$comment\n";   
  $counter2 = param('counter');
  for ($i=1; $i <= $counter2; $i++) {
     if (param("host$i") ne "") {
        print FILE param("host$i").'.'.param("agent$i");
        if (param("time$i") ne "") {
           print FILE '{'.param("time$i").'}';
        }
        @temparray = ('check','router','prio','down','up','delay','repeat','repeatprio','norepeat','keep','mail','msgmax','pager','trap','postpone','postpone_to');
        foreach $tempvar (@temparray) {
           if (param("$tempvar$i") ne "") {
              print FILE ' '.$tempvar.'='.param("$tempvar$i");
           }
        }
        print FILE "\n";
     }
  } 
  close(FILE);
  undef %param;
  
  print "<FONT SIZE=+2><CENTER>Changes successfully uploaded to config file</CENTER></FONT>\n";
  print hr({width=>'50%', align=>center});
  @temparray = `cat ${BSPATH}/adm/bb_event_generator.cfg`;
  print pre("@temparray");
  print hr({width=>'50%', align=>center});

  print start_form(-action=>'/cgi-bin/bsnotify');
  print submit({-name=>'RELOAD'});
  print end_form();
  exit;

}

$counter = 0;
$counter2 = 0;
@temparray = ();
$tempvar = "";

open(FILE,"+<${BSPATH}/adm/bb_event_generator.cfg") || die "Error -- Cant open config file\n";
while(<FILE>) {
  undef($timeline);
  chomp;
  next unless( $_ );   		# SKIP BLANK LINES
  next if( /^#/ );		# SKIP COMMENT LINES
  if ( /\\(\s)*$/ ) {		# LOOK FOR LINES WITH "\" CONTINUATION MARKER AT END
     $templine .= $_;
     next;
  } else {			# CYCLED THROUGH ALL (IF ANY) CONTINUATIONS
     $templine .= $_;
     $templine =~ s/\\/ /g;	# REMOVE CONTINUATION BACK-SLASHES
  }
  if ($templine =~ m/^ ## COMMENT:/) {
     if ($templine =~ m/^ ## COMMENT:Last modified/) {
	$lastmod = $templine;
        $lastmod =~ s/ ## COMMENT://g;
     } else {
	$comment .= $_;
	$comment =~ s/ ## COMMENT://g;
     }
     $templine = "";
  } else {
     if ($templine =~ m/\{/) {
       ($junk,$timeline) = split('\{', $templine);
       ($timeline,$junk) = split('\}', $timeline);
       @temp = split(' ',$templine);
     } else {
       @temp = split(' ',$templine);
     }
     $templine = "";
     $counter ++;
     foreach $data (@temp) {
        if ($data eq $temp[0]) {				# FIRST COLUMN (host.agent)
	   ( $rows{"host$counter"}, $rows{"agent$counter"} ) = split( '\.', $data);
	   if (defined $timeline) {
	      $rows{"time$counter"} = $timeline;
	   }
        } elsif ( $data =~ /=/ ) {				# KEY=VALUE COLUMN
     	   ($colname,$value) = split('=',$data);
     	   $rows{"${colname}$counter"} = $value;
        } else {
     	   $rows{"${colname}$counter"} .= " $data";
        }
     }
  }
}
close(FILE);

$flag = "";
open(BBCFG, "<${BSPATH}/adm/bb-display.cfg") || die "Cannot open bb-display.cfg\n";
while(<BBCFG>) {
  $tempvar = $_;
  next unless( $_ );
  if ( m/^# BEGIN GROUPS/ ) {
     $flag = "groups";
  } 
  if ( m/^# BEGIN HOSTS/ ) {
     $flag = "hosts";
  } 
  if ( m/^# END OF HOSTS/ ) {
     $flag = "";
  } 
  next if( m/^#/ );
  next if( m/^%/ );
  next if( m/^$/ );
  if ( $tempvar =~ m/^(.*)\((.*)\)/ ) {
     if ($flag eq "groups") {
	# GROUP
  	push(@sortme, "@".lc($1));
     } elsif ($flag eq "hosts") {
	# HOST
  	push(@sortme, lc($1));
     } 
  }
}
close(BBCFG);
@machines = sort(@sortme);

@sortme=();
%temparray=();
@agents=();
open(AGENTLOG, "<${BSPATH}/var/agent.log") || die "Cannot open agent.log\n";
while(<AGENTLOG>) {
  $tempvar = $_;
  next unless( $_ );
  next if( m/^#/ );
  next if( m/^$/ );
  if ( $tempvar =~ m/^.*\.(.*)\t.*/ ) {
  	push(@sortme, ($1));
  }
}
close(AGENTLOG);
@tempagents = grep(! $temparray{$_}++, @sortme);
@agents = sort(@tempagents);


print "<STYLE TYPE='text/css'><A:link {text-decoration: none}A:visited{text-decoration:none}A:active{text-decoration:none}></STYLE>\n";

print start_form(-action=>'/cgi-bin/bsnotify');
print "$FONT <A HREF='/bs/help/bb_event_generator.html#comment'>COMMENT:</FONT></A><BR>";
print textarea(-name=>'comment', -default=>"$comment", -rows=>5, -columns=>80);
print "<BR><A HREF='/bs/help/bb_event_generator.html#lastmod'>$lastmod</A></FONT><P>\n";
print start_table({-border=>2, -bordercolor=>'#666666', -bordercolorlight=>'#AAAAAA', -bgcolor=>'#444444', -cellpadding=>4});

print start_Tr();
   foreach $column (@colnames) {
      print td({-bgcolor=>'#333333', -align=>CENTER},[$FONT."<A HREF='/bs/help/bb_event_generator.html#".$column."' TARGET='helpwindow'>".uc($column)."</A>"]);
      print "\n";
   }
print end_Tr();

@tempmachines = ("");
push (@tempmachines, @machines);
$counter++;

for ($i=1; $i <= $counter; $i++) {   	# ITERATE THROUGH # LINES IN CONFIG FILE ($i)
   print start_Tr();
	$tempvar = "host$i";
	print td({-align=>CENTER},[popup_menu(-name=>"$tempvar", -value=>[@tempmachines], -default=>"$rows{$tempvar}")]); # "HOST" VALUE
	$tempvar = "agent$i";
	@temparray = ('*');
	push (@temparray, @agents);
	print td({-align=>CENTER},[popup_menu(-name=>"$tempvar", -value=>[@temparray], -default=>"$rows{$tempvar}")]); # "AGENT" VALUE
	$tempvar = "time$i";
	print td([textfield(-name=>"$tempvar", -value=>$rows{$tempvar})]); # "TIME" VALUE
	$tempvar = "check$i";
	print td([textfield(-name=>"$tempvar", -value=>$rows{$tempvar})]); # "CHECK" VALUE
	$tempvar = "router$i";
	print td([textfield(-name=>"$tempvar", -size=>4, -value=>"none")]); # "ROUTER" VALUE
	$tempvar = "prio$i";
	print td([textfield(-name=>"$tempvar", size=>3, -value=>$rows{$tempvar})]); # "PRIO" VALUE
	@temparray = ("","never","green","yellow","red","purple");
	$tempvar = "down$i";
	print td([popup_menu(-name=>"$tempvar", -value=>[@temparray], -default=>"$rows{$tempvar}")]); # "DOWN" VALUE
	$tempvar = "up$i";
	print td([popup_menu(-name=>"$tempvar", -value=>[@temparray], -default=>"$rows{$tempvar}")]); # "UP" VALUE
	$tempvar = "delay$i";
	print td([textfield(-name=>"$tempvar", size=>3, -value=>$rows{$tempvar})]); # "DELAY" VALUE
	$tempvar = "repeat$i";
	print td([textfield(-name=>"$tempvar", size=>3, -value=>$rows{$tempvar})]); # "REPEAT" VALUE
	$tempvar = "repeatprio$i";
	print td([textfield(-name=>"$tempvar", size=>3, -value=>$rows{$tempvar})]); # "REPEATPRIO" VALUE
	$tempvar = "norepeat$i";
	print td([textfield(-name=>"$tempvar", size=>3, -value=>$rows{$tempvar})]); # "NOREPEAT" VALUE
	$tempvar = "keep$i";
	print td([textfield(-name=>"$tempvar", size=>3, -value=>$rows{$tempvar})]); # "KEEP" VALUE
	$tempvar = "mail$i";
	print td([textfield(-name=>"$tempvar", size=>13, -value=>$rows{$tempvar})]); # "MAIL" VALUE
	$tempvar = "msgmax$i";
	print td([textfield(-name=>"$tempvar", size=>3, -value=>$rows{$tempvar})]); # "MSGMAX" VALUE
	$tempvar = "pager$i";
	@temparray = ("","notify");
	print td([popup_menu(-name=>"$tempvar", -value=>[@temparray], -default=>$rows{$tempvar})]); # "PAGER" VALUE
	$tempvar = "trap$i";
	print td([textfield(-name=>"$tempvar", size=>13, -value=>$rows{$tempvar})]); # "TRAP" VALUE
	$tempvar = "postpone$i";
	print td([textfield(-name=>"$tempvar", size=>3, -value=>$rows{$tempvar})]); # "POSTPONE" VALUE
	$tempvar = "postpone_to$i";
	@temparray = ("");
	push (@temparray, qw/00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23/);
	print td([popup_menu(-name=>"$tempvar", -value=>[@temparray], -default=>$rows{$tempvar})]); # "POSTPONE_TO" VALUE
	$tempvar = "";

	# for ($j=14; $j <= 15; $j++) {		# ITERATE THROUGH EACH FIELD IN ROW
	   # $tempvar = "$colnames[$j]$i";	# CREATE KEY FOR MATRIX AS COLNAME{ROW#} (i.e. HOST1)
	   # print td({-align=>CENTER},["$rows{$tempvar}"]); 	# PULL VALUE FOR KEY
	# }
   print end_Tr();
}
print end_table();
print p;
print hidden(-name=>'username', -value=>$username);
print hidden(-name=>'counter', -value=>$counter);
print submit({-name=>'SUBMIT'});
print reset({-name=>'RESET'});
print end_form();

print start_form(-action=>'/bs/help/bb_event_generator.html', -method=>get, -target=>'helpwindow');
print submit({-name=>'HELP'});
print end_form();

print end_html;
