#!/usr/bin/perl -w
#
# This is John Chambers' CGI script to take the output of the
# saying command and deliver it as a web page.  Look for the
# Sayings file for the data used by these programs.

$| = 1;
($P = $0) =~ s".*/"";
$V = $ENV{"V_$P"} || 3;
$inHTML = 1;
print "Content-type: text/html; charset=utf-8\n\n";
print "<html><head>\n";
print "<title>Saying of the day from " . `hostname` . "</title>\n";
print "</head><body>\n";
print "$P: V=$V.<br>\n";

$looping = ($0 =~ /s$/) ? 100 : 1;	# Loop at most 100 times
$ENV{"PATH"} = '.:' . $ENV{"PATH"};
$cmd = 'saying';
$cwd = `pwd`;
print "CWD: $cwd V=$v.<br>\n" if $V>0;
$pth = `which $cmd`;
print "CMD: $pth<br>\n" if $V>2;

if ($n = $ENV{'PATH_INFO'}) {
	$n =~ s/\D+//g;
	print "Saying $n:<p>\n";
	$cmd .= " $n";
}
loop:
	while ($looping) {
	@txt = `$cmd`;
	print "Cookie $looping:<br>\n" if $V>1;
	for $line (@txt) {
		$line =~ s/[\s\r]+$//;
		print "<br>Line: \"$line\"<br>\n" if $V>1;
		($pfx,$msg) = ($line =~ /^(\|*) ?(.*)$/);
		if ($pfx eq '|') {		# HTML?
			#
		} else {	# Plain text.
			if ($inPRE) {		# We're in a <pre> section
				print "</pre>";
				$inHTML = 1;
				$inPRE = 0;
			} elsif ($inPRE = $inHTML) {
				print "<pre>";
				$inHTML = 0;
			}
		}
		if ($inHTML) {
		#	$msg =~ s/^\s*//;
			$msg = "<P>" unless $msg;
		}
		print "\t$msg\n";
	}
	if ($inPRE) {
		print "</pre>";
		$inHTML = 1;
		$inPRE = 0;
	}
	if (--$looping > 0) {
		print "<hr><p>\n";
		sleep 10;
	}
}
print "</body>\n";

exit 0;
