#!/usr/bin/perl
use Socket;
use strict;
no strict "vars";

$root = "/etc";
$| = 1;
umask(0000);
Monitor();

sub Monitor {
  DAEMON: {
      local (@tmp_items,$conf_loc,@conf,@pinghosts,@tracehosts,@ruptimehosts,@ruptime2hosts,$sleeptime);
      my $arch_name;
      if ($pid = fork) {
	  ;
      } elsif (defined $pid) {
	  
	  @tmp_items = ();
	  $conf_loc = "";
	  @conf = ();
	  @pinghosts = ();
	  @tracehosts = ();
	  @ruptimehosts = ();
	  @ruptime2hosts = ();
	  
# Set Debug Level
#	  $D=4;
	  
# Mark temporary items that can be deleted
	  @tmp_items = ("idx","ping","trace","ruptime","printers","ifconfig","route","host");
	  
# Open default location file and read out data into a string
# named $conf_loc
	  $conf_loc = getConfLoc();
# Open actual configuration file now, knowing the location of it
	  @conf = getConf();
# Get the hosts that you want to ping
	  @pinghosts = getPingHosts();
# Get the hosts that you want to traceroute to
	  @tracehosts = getTraceHosts();
# Get the hosts you want to watch the load on
	  @ruptimehosts = getRuptimeHosts();
	  @ruptime2hosts = getRuptime2Hosts();
# Get the printer names to watch
	  @printers = getPrinters();
# Generate relevant HTML files and then clean up
	  
	  genHTML();
	  $arch_name = prep_archive();
	  sleep(60);
	  BuildAndClean();
	  archive($arch_name);
	  if ($conf{'update'} >= 0) {
	      if (lc($ARGV[0]) ne "once") {
		  $sleeptime = ($conf{'update'} - 1) * 60;
		  sleep($sleeptime);
		  redo DAEMON;
	      }
	  }
      } elsif ($! =~ /No more process/) {
	  sleep 5;
	  print "Possible problems with forking... Trying again...\n";
	  redo DAEMON;
      } else {
	  die "Can't fork at all!! :  $!\n";
      }
  }
}


# Strip off trailing \n or \r\n when necessary
sub stripCR {
    my $item = shift;
    my $len=length($item);
    if (substr($item,$len-1,1) eq "\n") {
	chop($item);
    }
    $len=length($item);
    if (substr($item,$len-1,1) eq "\r") {
	chop($item);
    }
    return $item;
}

sub ping {
    my $host = shift;
    my $port=13;
    my $iaddr = inet_aton($host) or die "no host: $host\n";
    my $paddr = sockaddr_in($port,$iaddr);
    my $proto = getprotobyname('tcp');
    $port=getservbyname($port,'tcp');
    socket(SOCK,PF_INET,SOCK_STREAM,$proto) or die "socket: $!\n";
    connect(SOCK,$paddr) or die "Connect : $!\n";
    close(SOCK);
    return(1);
}

sub stripSlash {
    my $item = shift;
    my $len = length($item);
    if (substr($item,$len-1,1) eq "/") {
	chop($item);
    }
    if (substr($item,$len-2,2) eq "\\\\") {
	chop($item);
	chop($item);
    }
    return($item);

}

sub Sysping {
	my $host = shift;
	my $ret;
	my $command = "$conf{'ping'} $host ";
	my $io = "$conf{'tmp'}/ping.$host";
	my $ioline;
	my $dest = "$conf{'hthome'}/Sysping.$host.html";
	my $date = getTime();
	open(SYSPING,">$dest") or die "Can't open sysping file: $!\n";
	print SYSPING <<SYSP1;
<!--- monitor, by Tom Kunz, tkunz\@redeemer.rutgers.edu.>
<!--- This program is made for the express purpose of making my life easier!>
<!--- These are automatically generated ping results.>
<!--- This file is automatically generated and will be changed automatically.>

<title>MONITOR: Sysping Results: $host</title>
<body bgcolor="#707070" text="#ffffff" link="#fff000">
<center><img src="monitor.gif"></center>
<h1 align=center> Sysping results: $host<br>
$date
</h1>
<h3>Automatically generated results from the command  "$command"</h3>
<p>
<pre>
SYSP1
	$ret = genSysExec("$command > $io");
	if ($ret == 0) {
	    open(SYSPIO,"$io") or ERR("lp", "Cant open sysping HTML file: $!\n");
	    while($ioline=<SYSPIO>) {
		print SYSPING $ioline;
	    }
	    close(SYSPIO);
	    chmod 0644,"$io";
	} else {
	    print SYSPING "Did not execute system shell properly.  Check configs.\n";
	}
	print SYSPING "</pre>\n";
	print SYSPING "<hr>\n";
	print SYSPING &Tail;
	close(SYSPING);
	chmod 0644,"$dest";
	return($ret);
}

sub PrnStat {
	my $host = shift;
	my $ret;
	my $command = "$conf{'prnstat'}";
	my $io = "$conf{'tmp'}/printers.$host";
	my $ioline;
	my $dest = "$conf{'hthome'}/printers.$host.html";
	my $date = getTime();
	$command =~ s/HOST/$host/gsx;
	open(SYSPING,">$dest") or die "Can't open printers file: $!\n";
	print SYSPING <<SYSP1;
<!--- monitor, by Tom Kunz, tkunz\@redeemer.rutgers.edu.>
<!--- This program is made for the express purpose of making my life easier!>
<!--- These are automatically generated printer statistics.>
<!--- This file is automatically generated and will be changed automatically.>

<title>MONITOR: Printer Results: $host</title>
<body bgcolor="#707070" text="#ffffff" link="#fff000">
<center><img src="monitor.gif"></center>
<h1 align=center> Printer Results: $host<br>
$date
</h1>
<h3>Automatically generated results from the command  "$command"</h3>
<p>
<pre>
SYSP1
	$ret = genSysExec("$command > $io");
	if ($ret == 0) {
	    open(SYSPIO,"$io") or ERR("lp", "Cant open printer HTML file: $!\n");
	    while($ioline=<SYSPIO>) {
		print SYSPING $ioline;
	    }
	    close(SYSPIO);
	    chmod 0644,"$io";
	} else {
	    print SYSPING "Did not execute system shell properly.  Check configs.\n";
	}
	print SYSPING "</pre>\n";
	print SYSPING "<hr>\n";
	print SYSPING &Tail;
	close(SYSPING);
	chmod 0644,"$dest";
	return($ret);
}

sub Tail {
    $item = "";
    $item .=  "<h4>\n";
    $item .=  "[<a href=\"$conf{'index'}\">Index</a>]<br>\n";
    $item .=  "[<a href=\"ping.html\">Ping Index</a>]<br>\n";
    $item .=  "[<a href=\"traceroute.html\">Traceroute Index</a>]<br>\n";
    $item .=  "[<a href=\"localroute.html\">Local Route / Ifconfig information</a>]<br>\n";
    $item .=  "[<a href=\"uptime.html\">Ruptime Listing using $conf{'ruptime'}</a>]<br>\n";
    $item .=  "[<a href=\"uptime2.html\">Ruptime Listing using $conf{'ruptime2'}</a>]<br>\n";
    $item .=  "[<a href=\"printers.html\">Printer Listing</a>]<br>\n";
    $item .=  "[<a href=\"flags.html\">Flag Index</a>]<br>\n";
    
    if("$conf{'email'}" ne "") { 
	$item .=  "[<a href=\"mailto:$conf{'email'}\">Mail MonitorMaster</a>]\n";
    }
    $item .=  "</h4><br>\n";
    return ($item);
}    

sub genIndex {
    my $idx = "$conf{'hthome'}/$conf{'index'}";
    my $line;
    my $date = getTime();

    open(IDX,">$idx") or die "Can't open master index $idx : $!\n";
    print IDX <<IDX1;
<!--- Welcome to MONITOR, a web-based monitoring system for networks>
<!--- monitor, by Tom Kunz, tkunz\@redeemer.rutgers.edu>
<!--- Developed with Linux Administrators in mind, but with the flexibility>
<!--- of running under Windows 95/NT as well as most unix systems!>
<title>Welcome to MONITOR!</title>
<body bgcolor="#707070" text="#ffffff" link="#fff000">
<center><img src="monitor.gif"></center>
<h1 align=center>Welcome to the Monitor!<br>
$date
</h1>
<hr>
<h3><b>Ping services:</h3></b></h3>
<h4>
<ul>
<a href="ping.html">System-level Ping</a>
</ul>
</h4>
<h3><b>TraceRoute information:</b><br></h3>
<h4>
<ul>
<li><a href="localroute.html">Local Routing Table</a><br>
<li><a href="traceroute.html">System Routes </a><br>
</ul>
</h4>
<h3><b>Uptime Information:</b></h3>
<h4>
<ul>
<li><a href="uptime.html">Remote Uptimes using $conf{'ruptime'}</a><br>
<li><a href="uptime2.html">Remote Uptimes using $conf{'ruptime2'}</a><br>
</ul>
</h4>
<h3><b>Printer Information:</b></h3>
<ul>
<h4><a href="printers.html">Printer List</a></h4>
</ul>
<h3><b>Warning Flags:</b></h3>
<ul>
<h4><a href="flags.html">Flags</a></h4>
</ul>

IDX1
    print IDX "<hr>\n";
    if ($conf{'email'} ne "") {
	print IDX "<i><a href=\"mailto:$conf{'email'}\">$conf{'email'}</a></i>\n";
    }
    print IDX "</body>\n";
    close(IDX);
    chmod 0644,"$idx";
#
#
# Insert code to generate the documents referenced here
#
#

}

#sub SysTime {
#    my $host = shift;
#$_[0];
#    my ($port,$iaddr,$paddr,$proto,$line);
#    $port = 13;
#    if ($host eq ""){
#	$ret = genSysExec("$conf{'date'} > $conf{'tmp'}/date.$$");
#	if ($ret == 0) {
#	    open(TMP,"$conf{'tmp'}/date.$$") or ERR("l","Cant open temp date file: $!\n");
#	    $line = <TMP>;
#	    $line = stripCR($line);
#	    return $line;
#	} else {
#	    return "No valid date found";
#	}
#    }
#    $port = getservbyname($port,'tcp');
#    die "Port Error: $!\n" unless $port;
#    $iaddr = inet_aton($host) or die "No such host: $host\n";
#    $paddr = sockaddr_in($port,$iaddr);
#    $proto = getprotobyname('tcp');
#    socket(SOCK,PF_INET,SOCK_STREAM,$proto) or die "Socket: $!\n";
#    connect(SOCK,$paddr);
#    $date = <SOCK>;
#    close (SOCK);
#    $date = stripCR($date);
#    return $date;
#}

sub CleanTmp {
	my ($ret,$time,$item);
	if ($D) {$time=getTime();}
	touchTmp();
	if ($D) {ERR("lp","$time : Cleaning house");}
	foreach $item (@tmp_items) {
		if ($D) {$time=getTime();}
		if ($D) {ERR("lp","$time : $conf{'delete'} $conf{'tmp'}/$item\*");}
		$ret = genSysExec("$conf{'delete'} $conf{'tmp'}/$item\* > $conf{'null'}");
		if ($D) {ERR("lp","$time : Returned $ret");}
    }
}

sub logger {
	my $item = shift;
#$_[0];
	my $len = length($item);
	open(LOG,">>$conf{'log'}") or badlog();
	print LOG $item;
	if (substr($item,$len-1,1) ne "\n") {
		print LOG "\n";
	}
 
}

sub badlog {
		warn "Can't open logfile, \"$conf{'log'}\": $!\n";
		open(W,">>$conf{'syslog'}") or warn "Can't open system log, either: $!\n";
		print W "Can't open logfile: $!\n";
		close(W);
}

sub comment {
	my $item = shift;
#$_[0];
	$item =~ s/ //gs;
	$item =~ s/\n//gs;
	if ((substr($item,0,1) eq "#") or ($item eq "")) {
		return(1);
	} else {
		return(0);
	}
}

sub getTime {
	my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
	my @days = ("Sun","Mon","Tue","Wed","Thu","Fri","Sat");
	my @months = ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
	$wday = $days[$wday];
	$mon = $months[$mon];
	$year +=1900;
	if ($mday < 10) {
		$mday = "0".$mday;
	}
	if ($hour < 10) {
		$hour = "0".$hour;
	}
	if ($min < 10) {
		$min = "0".$min;
	}
	if ($sec < 10) {
		$sec = "0".$sec;
	}
	return("$wday $mon $mday $hour:$min:$sec $year");
}

sub getConfLoc {
	my ($loc_line,$conf_loc);
	chmod 0644,"$root/monitor.loc";
	open(LOC,"$root/monitor.loc") or open(LOC,"./monitor.loc") or warn "Can't open location file: $!\n";
	while ($loc_line = <LOC>) {
		if (not comment($loc_line)) {
			$conf_loc = $loc_line;
		}
	}
	close(LOC);
	$conf_loc=stripCR($conf_loc);
	$conf_loc=stripSlash($conf_loc);
	return($conf_loc);
}

sub getConf {
# Log the fact that the monitor is starting
	my ($tmp,$len,$line,$key,$val,@conf,$StartTime);
	chmod 0644,"$conf_loc/monitor.conf";
	open(CONF,"$conf_loc/monitor.conf") or die "Can't open configuration file: $!\n";
	while(comment($line=<CONF>)) {;}
	($key,$val)=split("=",$line);
	$val = stripCR($val);
	$conf{$key}=$val;
	$StartTime = getTime();
	if ($conf{'log'}) {
		if ($D) {ERR ("lp","---Starting Monitor---\n");}
		if ($D) {ERR ("lp","$StartTime\n");}
		if ($D) {ERR ("lp","Using $conf_loc for configuration file location\n");}
	    }
#	if ($D > 2){ERR("lp","Using $conf_loc for configuration file location\n");}
	if ($D) {ERR("lp","Setting hash values\n");}
	while($line=<CONF>){
		($line)=stripCR($line);
		($key,$val)=split("=",$line);
		if (not comment($key)){
			$conf{$key}=$val;
#			if($D){print ("\t setting $key to $conf{$key}\n");}
			if (($D > 2) and ($conf{'log'})) {ERR("lp","setting $key to $conf{$key}\n");}
		}
	}
	close(CONF);
	if($conf{'sys'}) {$conf{'sys'} = lc($conf{'sys'});}
	if (not $conf{'null'}) {
		if ($conf{'sys'} eq "win95+") {
			$conf{'null'} = "NUL";
		} else {
			$conf{'null'} = "/dev/null";
		}
	}

# Converting slashes & backslashes
	if ($conf{'sys'} eq "win95+") {
		if ($D) {ERR ("p","System Type is Windows95, NT or similar");}
		if ($D) {ERR ("p","Converting / to \\ in configuration values");}
		foreach $key (sort keys %conf) {
			$conf{$key} =~ s/\//\\/gsx;
		}
	}
	return(@conf);
}

sub genSysExec {
    my $item=shift;
    my $ret;
    if ($conf{'sys'} eq "win95+") {
	$item =~ s/\//\\/gsx;
    }
    $ret = system("$item");
    return($ret);
}

sub touchTmp {
	my $item;
	my $time;
	$time = getTime();
	foreach $item (@tmp_items) {
		open(TMP,">>$conf{'tmp'}/$item") or ERR("l","$time : Unable to touch \"$item\" for cleanup: $!\n");
		close(TMP);
	}
}

sub genHTML {
	my $time = getTime();
	if ($D) {ERR("l","$time : Touching Flag File");}
	touchFlags();
	if ($D) {ERR("l","$time : Generating Ping Stats");}
	genPing();
	if ($D) {ERR("l","$time : Generating Traceroute Stats");}
	genTrace();
	if ($D) {ERR("l","$time : Generating Ruptime Stats");}
	genUptime();
	if ($D) {ERR("l","$time : Generating Ruptime2 Stats");}
	genUptime2();
	if ($D) {ERR("l","$time : Generating Route Stats");}
	genRoute();
	if ($D) {ERR("l","$time : Generating Printer Stats");}
	genPrn();
	if ($D) {ERR("l","$time : Generating Index of Results");}
	genIndex();
#	MakeIndex("ping");
#	MakeIndex("trace");
#	MakeIndex("printers");
#	MakeIndex("ruptime");
#	MakeIndex("ruptime2");
}

sub getPingHosts {
	my @hosts = getHosts("ping");
	return @hosts;
}

sub getRuptimeHosts {
	my @hosts = getHosts("ruptime");
	return @hosts;
}

sub getRuptime2Hosts {
	my @hosts = getHosts("ruptime2");
	return @hosts;
}

sub getPrinters {
	my @hosts = getHosts("printers");
	return @hosts;
}

sub getHosts {
	my $type = shift;
#$_[0];
	my $time = getTime();
	my $line,$inc_line;
	my @hosts;
	my $name;
#	if (lc($type) eq "ping") {$name = "ping.hst";}
#	if (lc($type) eq "trace") {$name = "trace.hst";}
#	if (lc($type) eq "ruptime") {$name = "ruptime.hst";}
#	if (lc($type) eq "printers") {$name = "printers.hst";}
#	open(PH,"$conf_loc/$name") or ERR("l","$time : Can't open $type hosts file : $!");

	if (lc($type) eq "ping") {$name = "$conf{'pinglist'}";}
	if (lc($type) eq "trace") {$name = "$conf{'tracelist'}";}
	if (lc($type) eq "printers") {$name = "$conf{'printerlist'}";}
	if (lc($type) eq "ruptime") {$name = "$conf{'ruptimelist'}";}
	if (lc($type) eq "ruptime2") {$name = "$conf{'ruptime2list'}";}
	open(PH,"$name") or ERR("l","$time : Can't open $type hosts file : $!");
	while (not comment($line=<PH>)) {
		if (lc(substr($line,0,7)) eq "include") {
			($inc,$newloc)=split("=",$line);
			$newloc=stripCR($newloc);
			$time = getTime();
			open(INC,"$newloc") or ERR("l","$time : Unable to open $newloc : $!");
			while($inc_line = <INC>) {
				$inc_line = stripCR($inc_line);
				if (lc(substr($inc_line,0,8)) eq "include=") {
				    ERR("lfp","You included in an include file in \"$newloc\".  Please remove include statement from $newloc.","LOCALMACHINE");
				    goto SKIPINCLUDE;
#				    $inc_line = "";
				}
				@hosts = (@hosts, stripCR($inc_line));
			      SKIPINCLUDE:
#				print $inc_line;
			}
			close(INC);
#			print("$inc is $newloc\nnextline\n");
		} else {
			@hosts = (@hosts,stripCR($line));
		}
	}
	close(PH);
	return(@hosts);
}

sub getTraceHosts {
	my @hosts = getHosts("trace");
	return @hosts;

}

sub genPing {
    my $host;
    my $time;
    foreach $host (@pinghosts) {
	$time = getTime();
	if ($D) {ERR("lp","$time : pinging: $host");}
#	print ("$time : pinging: $host\n");
	genericThread("ping",$host);
#	Sysping("$host");
#		ping($host);
    }
#    MakeIndex("ping");
}

sub genPrn {
    my $host;
    my $time;
    foreach $host (@printers) {
	$time = getTime();
	if ($D) {ERR("lp","$time : PrnStat $host");}
	genericThread("printers",$host);
    }
#    MakeIndex("printers");
}

sub genTrace {
    my $host;
    my $time;
    foreach $host (@tracehosts) {
	$time = getTime();
	if ($D) {ERR("lp","$time : tracing: $host");}
#	print("$time : tracing: $host\n");
	genericThread("trace",$host);
#		Systrace($host);
    }
#    MakeIndex("trace");
}

sub Systrace {
	my $host = shift;
	my $ret;
	my $command = "$conf{'traceroute'} $host ";
	my $io = "$conf{'tmp'}/trace.$host";
	my $ioline;
	my $dest = "$conf{'hthome'}/trace.$host.html";
	my $date = getTime();
	open(SYSTRACE,">$dest") or die "Can't open systrace HTML file: $!\n";
	print SYSTRACE <<SYST1;
<!--- monitor, by Tom Kunz, tkunz\@redeemer.rutgers.edu.>
<!--- This program is made for the express purpose of making my life easier!>
<!--- These are automatically generated ping results.>
<!--- This file is automatically generated and will be changed automatically.>

<title>MONITOR: Systrace Results: $host</title>
<body bgcolor="#707070" text="#ffffff" link="#fff000">
<center><img src="monitor.gif"></center>
<h1 align=center> Systrace results: $host<br>
$date</h1>
<h3>Automatically generated results from the command  "$command"</h3>
<p>
<pre>
SYST1
	$ret = genSysExec("$command > $io");
	if ($ret == 0) {
	    open(SYSTIO,"$io") or ERR("lp","Cant open sytrace IO file: $!\n");
	    while($ioline=<SYSTIO>) {
		print SYSTRACE $ioline;
	    }
	    close(SYSTIO);
	    chmod 0644,"$io";
	} else {
	    print SYSTRACE "Did not execute system shell properly.  Check configs.\n";
	}
	print SYSTRACE "</pre>\n";
	print SYSTRACE "<hr>\n";
	print SYSTRACE &Tail;
	close(SYSTRACE);
	chmod 0644,"$dest";
	exit(0);
	return($ret);

}

sub REAPER {
        $SIG{CHLD} = \&REAPER;
        $waitedpid = wait;
}


sub genericThread {
    my ($op,$host) = @_;
    my $pid;
    my $time;
   if(!defined($pid = fork)) {
	$time = getTime();
	print "Cant fork: $!";
	if ($D) {ERR("lfp","$time : Forking error: $!","monitor-home");}
	return;
    } elsif ($pid) {
	if ($D > 4) {
	    $time = getTime();
	    ERR("l","$time : Begatting a Fork: $pid $op $host");
	}
	return;
    }
    if ($D > 4) {
	$time = getTime();
	ERR("l","$time : Running the Fork: $pid $op $host");
   }
    if ($op eq "ping") {
	Sysping($host);
    } elsif ($op eq "trace") {
	Systrace($host);
    } elsif ($op eq "ruptime") {
	MonRuptime($host);
    } elsif ($op eq "ruptime2") {
	MonRuptime2($host);
    } elsif ($op eq "printers") {
	PrnStat($host);
    }

    if ($D > 4) {
	$time = getTime();
	ERR ("l","$time : Fork is Closing: $pid $op $host");
    }
    exit();
}

sub MakeIndex {
    my $type = lc(shift);
    my $command,$ret,$time,$line,$line2,$Up,$toss,$hostname;
    my $tmp = "$conf{'tmp'}/$type.idx.tmp";
    my $dest;
    my $date = getTime();
    if ($type eq "ping") {
	$dest = "$conf{'hthome'}/ping.html";
	$command = "$conf{'directory'} Sysping.\*.html > $tmp";
#	print("I am of $type\n");
#	print ("I should do $command and have $dest\n");
    } elsif ($type eq "trace") {
	$dest = "$conf{'hthome'}/traceroute.html";
	$command = "$conf{'directory'} trace.\*.html > $tmp";
#	print("I am of $type\n");
#	print ("I should do $command and have $dest\n");
    } elsif ($type eq "printers") {
	$dest = "$conf{'hthome'}/printers.html";
	$command = "$conf{'directory'} printers.\*.html > $tmp";
    } elsif ($type eq "ruptime") {
	$dest = "$conf{'hthome'}/uptime.html";
	$command = "$conf{'directory'} $conf{'tmp'}/ruptime.\*.raw > $tmp";
	system($command);
	open(RUPTIME,">$dest") or ERR("lp","Could not create RUPTIME listing: $!\n ");
	print RUPTIME <<RUP;
<!--- monitor, by Tom Kunz, tkunz\@redeemer.rutgers.edu.>
<!--- This program is made for the express purpose of making my life easier!>
<!--- This the $type listing.>
<!--- This file is automatically generated and will be changed automatically.>

<title>MONITOR: Ruptime Listing</title>
<body bgcolor="#707070" text="#ffffff" link="#fff000">
<center><img src="monitor.gif"></center>
<h1 align=center> Ruptime Listing<br>
$date
</h1>
<h3>Automatically generated listing
<hr>
Results from the following machines are available:<br>
</h3>
<h4>
<pre>
RUP
    ;
        open(RUPTEMP,"$tmp") or ERR("lp","Could not open $tmp : $!\n");
	while ($line = <RUPTEMP>) {
	    $line = stripCR($line);
	    open(RUPT2,"$line") or ERR("lp","Could not open $line : $!\n");
	    while ($line2 = <RUPT2>) {
		print RUPTIME $line2;
#		print $line2,"\n";
	    }
	    close(RUPT2);
	}
	close(RUPTEMP);
	print RUPTIME "</pre>";
	print RUPTIME &Tail;
	close RUPTIME;
	chmod 0644,$dest;
	return();
    } elsif ($type eq "ruptime2") {
	$dest = "$conf{'hthome'}/uptime2.html";
	$command = "$conf{'directory'} $conf{'tmp'}/ruptime2.\*.raw > $tmp";
	system($command);
	open(RUPTIME2,">$dest") or ERR("lp","Could not create RUPTIME2 listing: $!\n ");
	print RUPTIME2 <<RUP2;
<!--- monitor, by Tom Kunz, tkunz\@redeemer.rutgers.edu.>
<!--- This program is made for the express purpose of making my life easier!>
<!--- This the $type listing.>
<!--- This file is automatically generated and will be changed automatically.>

<title>MONITOR: Ruptime Listing</title>
<body bgcolor="#707070" text="#ffffff" link="#fff000">
<center><img src="monitor.gif"></center>
<h1 align=center> Ruptime Listing<br>
$date
</h1>
<h3>Automatically generated listing
<hr>
Results from the following machines are available:<br>
</h3>
<h4>
<pre>
RUP2
    ;
        open(RUPTEMP2,"$tmp") or ERR("lp","Could not open $tmp : $!\n");
	while ($line = <RUPTEMP2>) {
	    $line = stripCR($line);
	    open(RUPT22,"$line") or ERR("lp","Could not open $line : $!\n");
	    while ($line2 = <RUPT22>) {
		print RUPTIME2 $line2;
#		print $line2,"\n";
	    }
	    close(RUPT22);
	}
	close(RUPTEMP2);
	print RUPTIME2 "</pre>";
	print RUPTIME2 &Tail;
	close RUPTIME2;
	chmod 0644,$dest;
	return();

    } else {
	$time = getTime();
	ERR("l","$time : Got an unknown type of index =  $type");
#	print "I just got $type, and I don't know what it is\n";
    }
#    print("I am going to do:\n $command\n");
    if (lc$conf{'sys'} eq "win95+") {
	$command =~ s/\//\\/gsx;
    }
    chdir($conf{'hthome'});
    $ret = system("$command");
#	if ($ret = 0) {
    $time = getTime();
#    print("Once and for all I got $dest ----------------------\n");
	    open(TMP,"$tmp") or ERR("l","$time : Cant open temp for $type index : $!");
	    open(D,">$dest") or ERR("l","$time : Cant open destination for $dest $type : $!");
	    $Up = uc($type);
#	    print "Making DESTINATION!\n";
	    print D <<InDeX;
<!--- monitor, by Tom Kunz, tkunz\@redeemer.rutgers.edu.>
<!--- This program is made for the express purpose of making my life easier!>
<!--- This the $type index.>
<!--- This file is automatically generated and will be changed automatically.>

<title>MONITOR: $Up Index</title>
<body bgcolor="#707070" text="#ffffff" link="#fff000">
<center><img src="monitor.gif"></center>
<h1 align=center> $Up Index<br>
$date
</h1>
<h3>Automatically generated index
<hr>
$Up Results from the following machines are available:<br>
</h3>
<h4>
<ul>
InDeX
		while ($line = <TMP>) {
		    $line = stripCR($line);
		    $hostname = $line;
#		    ($toss,@hostname) = split(/\./,$line);
		    $hostname =~ s/^trace\.//os;
		    $hostname =~ s/^Sysping\.//os;
		    $hostname =~ s/^printers\.//os;
		    $hostname =~ s/\.html$//os;

#		    print "Tossed $toss host - ",$hostname,"\n";
		    print D "<li><a href=\"$line\">",$hostname,"</a><br>\n";
#		    print D $line;
		}
    close(TMP);
    print D "</ul>\n<br>";
#	    if ($conf{'email'} ne "") {
#		print D "<hr><i><a href=mailto:$conf{'email'}>$conf{'email'}</a></i>\n";
#	    }
#	    print D "</body>\n</html>\n";
    print D "<hr>";
    print D &Tail;
#	}
    close(D);
    chmod 0644,"$dest";
}

sub ERR {
    my $type,$msg,$host;
    ($type,$msg,$host) = @_;
    $type = lc($type);
    $msg = stripCR($msg);

    if ($type eq "l") {
	if ($host ne "") {
	    logger("$msg => $host");
	} else {
	    logger("$msg");
	}
	return;
    } elsif ($type eq "f") {
	flag($msg,$host);
	return;
    } elsif ($type eq "p") {
	if ($host ne "") {
	    print("$msg => $host\n");
	} else {
	    print("$msg\n");
	}
	return;
    } elsif ($type eq "lf") {
	if ($host ne "") {
	    logger("$msg => $host");
	    flag($msg,$host);
	} else {
	    logger("$msg");
	    flag($msg,$host);
	}
	return;
    } elsif ($type eq "lp") {
	if ($host ne "") {
	    logger("$msg => $host"); 
	    print("$msg => $host\n");
	} else {
	    logger("$msg"); 
	    print("$msg\n");
	}
	return;
    } elsif ($type eq "fp") {
	flag($msg,$host);
	print("$msg => $host\n");
	return;
    } elsif ($type eq "lfp") {
	if ($host ne "") {
	    logger("$msg => $host");
	    flag($msg,$host);
	    print("$msg => $host\n");
	} else {
	    logger("$msg");
	    flag($msg,$host);
	    print("$msg\n");
	}
	return;
    } else {
	print "$type = Ambiguous ERR command, using lfp instead\n";
	ERR("lfp",$msg,$host);
	return;
    }
}

sub flag {
    my ($msg,$host) = @_;
    my $line,$flag_msgs;
    my $MSG = "No flags raised.";
    my $date = getTime();
    if ($host eq "") {
	return;
    }
    $msg = stripCR($msg);
    $flag_msgs = "";
    open(FLAGS,"$conf{'hthome'}/flags.raw") or 	$flag_msgs = $msg;
    if ($flag_msgs ne $msg) {
	while ($line = <FLAGS>) {
	    $flag_msgs .= $line;
	}
	close (FLAGS);
	$flag_msgs .= $msg,"\n";
    }
    open(FLAGS,">>$conf{'hthome'}/flags.raw") or ERR("lp","Could not open raw flag file for append: $!\n");
    print FLAGS $flag_msgs,"\n";
    close(FLAGS);
    open(FLAGHOST,">$conf{'hthome'}/flags.html") or ERR("lp","Could not open flag HTML file: $!\n");
    print FLAGHOST <<FLAG1;
<!--- monitor, by Tom Kunz, tkunz\@redeemer.rutgers.edu.>
<!--- This program is made for the express purpose of making my life easier!>
<!--- This the flag host index.>
<!--- This file is automatically generated and will be changed automatically.>

<title>MONITOR: Flagged Host Index</title>
<body bgcolor="#707070" text="#ffffff" link="#fff000">
<center><img src="monitor.gif"></center>
<h1 align=center> FLAG Index<br>
$date
</h1>
<h3>Automatically generated flag listing
<hr>
The following are flags received from various hosts while testing their availability:<br>
</h3>
<h4>
<pre>
$flag_msgs
</pre>
</h4>
<br>
FLAG1
    print FLAGHOST "<hr>\n";
    print FLAGHOST &Tail;
    print FLAGHOST "<hr>\n";
    close(FLAGHOST);
    chmod 0644,"$conf{'hthome'}/flags.html";

}

sub MonRuptime {
    my $host = shift;
    my $ret;
    my $ITERATE = 0;
    my $command = "$conf{'ruptime'} $host ";
    my $io = "$conf{'tmp'}/ruptime.$host.raw";
#    my $dest = "$conf{'hthome'}/uptime.$host.html";
#  SECOND:
#    my $ioline;
    
#    $ret = 
    genSysExec("$command > $io");
#    if ($ret == 0) {
#	open(RUPTIO,"$io") or ERR("lp","Cant open sytrace IO file: $!\n");
#	while($ioline=<RUPTIO>) {
#	    print RUPTRACE $ioline;
#	}
#	close(RUPTIO);
    chmod 0644,"$io";
#    } else {
#	ERR("lfp", "Value = \"$ret\".  Did not execute system shell properly, or \"$conf{'ruptime'} $host\" died.  Check configs.\n",$host);
#    }
#    print SYSTRACE "</pre>\n";
#    print SYSTRACE "<hr>\n";
#    print SYSTRACE &Tail;
#    close(SYSTRACE);
#    if ((!$ITERATE) and ($conf{'ruptime2'})) {
#	$ITERATE++;
#	$command = "$conf{'ruptime2'} $host";
#	$io = "$conf{'tmp'}/ruptime.ALT-RUP.$host.raw";
#	goto SECOND;
#    }
    exit(0);
#	return($ret);
    
}

sub MonRuptime2 {
    my $host = shift;
    my $ret;
    my $ITERATE = 0;
    my $command = "$conf{'ruptime2'} $host ";
    my $io = "$conf{'tmp'}/ruptime2.$host.raw";
#    my $dest = "$conf{'hthome'}/uptime.$host.html";
#  SECOND:
#    my $ioline;
    
#    $ret = 
    genSysExec("$command > $io");
#    if ($ret == 0) {
#	open(RUPTIO,"$io") or ERR("lp","Cant open sytrace IO file: $!\n");
#	while($ioline=<RUPTIO>) {
#	    print RUPTRACE $ioline;
#	}
#	close(RUPTIO);
    chmod 0644,"$io";
#    } else {
#	ERR("lfp", "Value = \"$ret\".  Did not execute system shell properly, or \"$conf{'ruptime'} $host\" died.  Check configs.\n",$host);
#    }
#    print SYSTRACE "</pre>\n";
#    print SYSTRACE "<hr>\n";
#    print SYSTRACE &Tail;
#    close(SYSTRACE);
#    if ((!$ITERATE) and ($conf{'ruptime2'})) {
#	$ITERATE++;
#	$command = "$conf{'ruptime2'} $host";
#	$io = "$conf{'tmp'}/ruptime.ALT-RUP.$host.raw";
#	goto SECOND;
#    }
    exit(0);
#	return($ret);
    
}


sub genUptime {
    my $host;
    my $time;
    foreach $host (@ruptimehosts) {
	$time = getTime();
	if ($D) {ERR("lp","$time : ruptime: $host");}
	genericThread("ruptime",$host);
    }
#    MakeIndex("ruptime");
}
sub genUptime2 {
    my $host;
    my $time;
    foreach $host (@ruptime2hosts) {
	$time = getTime();
	if ($D) {ERR("lp","$time : ruptime2: $host");}
	genericThread("ruptime2",$host);
    }
    $time = getTime();
    if ($D) {ERR("lp","$time : Creating ruptime2 Indices");}
#    MakeIndex("ruptime2");
}

sub touchFlags {
    my $existing = 1;
    my $date = getTime();
    open(FLAGS,"$conf{'hthome'}/flags.html") or $existing = 0;
    if($existing == 0) {
	open(FLAGS,">$conf{'hthome'}/flags.html") or ERR("lp","Error creating flag HTML file for the first time: $!\n");
	print FLAGS <<FLAG1;
<!--- monitor, by Tom Kunz, tkunz\@redeemer.rutgers.edu.>
<!--- This program is made for the express purpose of making my life easier!>
<!--- This the flagged host index.>
<!--- This file is automatically generated and will be changed automatically.>

<title>MONITOR: Flagged Host Index</title>
<body bgcolor="#707070" text="#ffffff" link="#fff000">
<center><img src="monitor.gif"></center>
<h1 align=center> FLAG Index<br>
$date
</h1>
<h3>Automatically generated index</h3>
<hr>
<h4>
There are no flags currently up.  This file is generated by the initial running of monitor and you can only see this message when everything is OK.  When a flag is raised on a particular system, you can view it by loading this page and seeing what the flagged message was.<br>
</h4>
<hr>
FLAG1
        print FLAGS &Tail;
	close(FLAGS);
	chmod 0644, "$conf{'hthome'}/flags.html";
    }
}

sub genRoute {
    my $ret;
    my $ifconfig_msg = "";
    my $route_msg = "";
    my $line;
    my $date = getTime();

    if ($conf{'ifconfig'}) {
	$ret = system("$conf{'ifconfig'} > $conf{'tmp'}/ifconfig.raw");
    }
    if ($ret != 0) {
	$ifconfig_msg = "$conf{'ifconfig'} failed miserably.  Check Configs.";
	ERR("lfp",$ifconfig_msg,"localhost");
    } else {
	open(IFCONFIG,"$conf{'tmp'}/ifconfig.raw") or ERR("lfp","$conf{'tmp'}/ifconfig.raw has a problem: $!\n");
	while ($line = <IFCONFIG>) {
	    $ifconfig_msg .= $line;
	}
	close(IFCONFIG);
    }
    if ($conf{'route'}) {
	$ret = system("$conf{'route'} > $conf{'tmp'}/route.raw");
    }
    if ($ret != 0) {
	$route_msg = "$conf{'route'} failed miserably.  Check Configs.";
	ERR("lfp",$route_msg,"localhost");
    } else {
	open(RT,"$conf{'tmp'}/route.raw") or ERR("lfp","$conf{'tmp'}/route.raw has a problem: $!\n");
	while ($line = <RT>) {
	    $route_msg .= $line;
	}
	close(RT);
    }
    open(ROUTE,">$conf{'hthome'}/localroute.html") or ERR("lfp","Can't open localroute HTML file: $!\n");
    print ROUTE <<RTE;
<!--- monitor, by Tom Kunz, tkunz\@redeemer.rutgers.edu.>
<!--- This program is made for the express purpose of making my life easier!>
<!--- This the local route and ifconfig output.>
<!--- This file is automatically generated and will be changed automatically.>

<title>MONITOR: Local Route / Ifconfig Output</title>
<body bgcolor="#707070" text="#ffffff" link="#fff000">
<center><img src="monitor.gif"></center>
<h1 align=center> Local Route / Ifconfig Output<br>
$date
</h1>
<h3>Automatically generated listing</h3>
<hr>
<h3>
$conf{'ifconfig'} output:
<pre>
$ifconfig_msg
</pre>
<hr>
$conf{'route'} output:
<pre>
$route_msg
</pre>
</h3>
RTE
    ;
    print ROUTE &Tail;
    close(ROUTE);
    chmod 0644,"$conf{'hthome'}/localroute.html";
}

sub prep_archive {
    my $subdir1,$subdir2,$subdir3,$ret,$archive_dir;
    my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
    my @days = ("Sun","Mon","Tue","Wed","Thu","Fri","Sat");
    $dayname = $days[$wday];
    $mon++;
    if ($mon < 10) {
	$mon = "0".$mon;
    }
    if ($wday < 10) {
	$wday = "0".$wday;
    }
    if ($mday < 10) {
	$mday = "0".$mday;
    }
    if ($hour < 10) {
	$hour = "0".$hour;
    }
    if ($min < 10) {
	$min = "0".$min;
    }
    if ($sec < 10) {
	$sec = "0".$sec;
    }
    $subdir1 = "$year$mon";
    $subdir2 = "$mday$dayname";
    $subdir3 = "$hour:$min:$sec";
    $archive_dir = "$subdir1/$subdir2/$subdir3";
    mkdir("$conf{'archive'}/$subdir1",0777);
    mkdir("$conf{'archive'}/$subdir1/$subdir2",0777);
    mkdir("$conf{'archive'}/$subdir1/$subdir2/$subdir3",0777);
    return ($archive_dir);
}

sub archive {
    my $archive_dir = shift;
    system("$conf{'copy'} $conf{'hthome'}/$conf{'wildcard'} $conf{'archive'}/$archive_dir > $conf{'null'} ");
    return;
}

sub BuildAndClean {
    MakeIndex("ping");
    MakeIndex("trace");
    MakeIndex("printers");
    MakeIndex("ruptime");
    MakeIndex("ruptime2");
    CleanTmp();
}
