#!/usr/local/bin/perl
$| = 1;

my $okToGoOn = 0;
my $remoteHost = $ENV{'REMOTE_HOST'};

if ($remoteHost =~ m!hfradio|donobi!i) {
	$okToGoOn = 1;
} else {
	$okToGoOn = 0;
}

if (! $okToGoOn) {
	print "Location: http://hfradio.org/swbc/\nURI: http://hfradio.org/swbc\n\n";
} else {

	use Pg;

	$downloadOK = 1;

	$solarReport = "";
	$mail_prog = '/usr/lib/sendmail' ;
	$theRootDir = "/home/hfradio/database/swl";
	$theLogFile = $theRootDir . "/lookups.log";

	$html_header = "Content-type: text/html\n\n";
	$templateDir = "/home/hfradio/html/hfstation";

	$gmtTime = `date -u +%H:%M:%S`;
	chop $gmtTime;
	$showTime = `date -u +%H%M`;
	chop $showTime;
	$gmtDay = `date -u +%Y-%m-%d`;
	chop $gmtDay;
		

	$styleSheet = "/home/hfradio/html/cgi-bin/styles.format";
	$theMenu = "/home/hfradio/html/cgi-bin/menu.format";

	$theLinks = "<a href=\"http://hfradio.org/cgi-bin/swllinks\" target=\"swlWin\">shortwave links</a>";

	$remoteHost = $ENV{'REMOTE_HOST'};

	&GetFormInput;
	doSolarData();

	my ($result, $conn);
	my ($message) = "";

	if (! $okToGoOn) {

		open (STYLE, "$styleSheet") || die "Could not read $styleSheet: $!\n";
		$_style = "";
		while (<STYLE>) {
			$_style .= $_;
		}
		close (STYLE);

		open (MENU, "$theMenu") || die "Could not read $theMenu: $!\n";
		$_menu = "";
		while (<MENU>) {
			$_menu .= $_;
		}
		close (MENU);

		print $html_header;
		print <<YE1;
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Shortwave Transmissions at $showTime</title>
$_style
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

</head>
<body background="http://hfradio.org/graphics/backmap.gif" bgcolor="#FFFFFF">
<div align="center">
<table width="100%"><tr>
<td valign=top>
<img src="http://hfradio.org/graphics/hfr-l.gif" width=171 height=82 border=0 alt="hfradio.org" vspace="0"><br>
<img src="http://hfradio.org/graphics/swl.gif" width=168 height=30 border=0 alt="SWL Search from NW7US" vspace="0">
</td>
<td>
<br><br>
$_menu
<br>
<div class="menu" align="center">
Do you need programming help or database engineering?<br>
<a href="http://custom.accessnow.com" target="wrkWin">See Tomas' Services</a>
<br><br>
$solarReport
</div>

</td>
</tr>
</table>
</div>
<hr noshade>
<div align=center>
Hello.
<br><br>
<b>Please use the following link for now:</b> 
<a href="http://hfradio.org/swbc/">http://hfradio.org/swbc/</a>
<br><br>
<hr noshade width="400">
</div>

<div>
<blockquote>
This page is currently down as I re-do the database with different data sources.
<br><br>
I am trying to work out with <a href="http://www.ilgradio.com/ilgradio.htm" target="ilgWin">Bernd 
Friedewald, of ILG</a> some kind of arrangement to obtain current data from him.
<br>
<br>
I am giving my apologies to Bernd for my misunderstanding. And, I have taken his database from 
public access at this page.
<br>
<br>
I await his reply to me.  I hope for a discussion with him. In the meantime, I am working on 
alternative sources and will recreate the database.  So hang in there.  I will attempt to 
provide a good look-up service for those who cannot handle huge amounts of data, or are at a 
place where they cannot store data on their local machine. 
<br>
<br>
In the meanwhile, please use this:
<br><br>
<a href="http://hfradio.org/swbc/">http://hfradio.org/swbc/</a><br><br>
</blockquote>
</div>
</body>
</html>
YE1

	} else {

		$conn = Pg::connectdb("dbname=swl user=tomas");

		if (! PGRES_CONNECTION_OK eq $conn->status) {

			$okToGoOn = 0;
			$message = "Error hooking up to the database.  Message is<br>";
			$message .= $conn->errorMessage . "<br>\n";
			print STDERR "No postgresql connection...\n";
					print $html_header;
					print <<YE2;
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><title>Database Down for a while...</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body bgcolor="FFFFFF">
<div align=center>
<font face="verdana" size="-1">
Hello.
<br><br>
The database is down right now.  Please try later.
</font>
</body>
</html>
YE2
		} else {
			@foundItems = ();

			%downloadList = ();

			if (exists ($field{'private'})) {
				$private = $field{'private'};
			}

			if (! exists ($field{'search'})) {
				&showForm(1);
			} else {

				$theSearch = $field{'freq'};

				$_theSearch = $theSearch;
				$_theSearch =~ s|^\s*(.*?)\s*$|$1|;
				if ($_theSearch =~ m|^voa$|i) {
					$_theSearch = "voice of america";
				}
				$_theSearch =~ s/\%/\\\%/g;
				$_theSearch =~ s/\_/\\\_/g;
				$_theSearch =~ tr/A-Z/a-z/;
				
				$_theSearch = "\%" . $_theSearch . "\%";
				print STDERR "Searching for [$_theSearch]\n";

				$result = $conn->exec("
					SELECT *
					FROM schedule_flat
					WHERE
						(LOWER(station) LIKE '$_theSearch') OR
						(LOWER(country) LIKE '$_theSearch')
				");
				if (!PGRES_TUPLES_OK eq $result->resultStatus) {
					$okToGoOn = 0;
					$message = "Error getting the data out of the database.  Message is<br>";
					$message .= $conn->errorMessage . "<br>\n";
				} else {
				
					while (@swl_field = $result->fetchrow) {
						my ($oid,$freq,$station,$utcTimeStart,$utcTimeEnd,$days,$lang,$country,$target,$location,$power,$azimuth,$remarks,$modulation,$long,$lat,$region,$program) = @swl_field;

						if ($power =~ m|^(\d+)\.000$|) {
							$power = $1;
						} elsif ($power =~ m|^[0]+\.(.*)|) {
							$power = $1;
						}

						$freq =~ tr/ //d;

						$utcTimeStart =~ tr/\://d;
						$utcTimeStart =~ m|(\d\d\d\d)\d\d|;
						$utcTimeStart = $1;
						$utcTimeEnd =~ tr/\://d;
						$utcTimeEnd =~ m|(\d\d\d\d)\d\d|;
						$utcTimeEnd = $1;
						$count++;
						my $utcTime = $utcTimeStart . "-" . $utcTimeEnd;
						my $newRec = "$freq\t$utcTime\t$station\t$days\t$lang\t$country\t$target\t$power";

						if (length($field{'lang'})) {
							if ($lang =~ m|$field{'lang'}|i) {
								push (@foundItems, $newRec);
							}
						} else {
							push (@foundItems, $newRec);
						}
					}
				}
				my $count = @foundItems;
				
				if ($count) {

					$tt = "<tr><td>_freq_</td><td>_time_</td><td>_station_</td><td>_country_</td><td>_days_</td><td>_lang_</td><td>_target_</td><td>_power_</td></tr>\n";

					$theTable = "<div>\n";
					$theTable .= "<blockquote>Yellow highlights current transmissions</blockquote>\n";
					$theTable .= "</div><div align=\"center\">\n";
					$theTable .= "<table width=\"95\%\" border=1 bgcolor=\"\#FFFFFF\"><tr><td><table border=0 cellpadding=3 cellspacing=0 width=\"100\%\">\n";
					$trh = $tt;
					$trh =~ s|<td>|<td align=center>|ig;
					$trh =~ s|_freq_|<b>FREQ</b>|ig;
					$trh =~ s|_time_|<b>Time</b>|ig;
					$trh =~ s|_station_|<b>Station</b>|ig;
					$trh =~ s|_country_|<b>Country</b>|ig;
					$trh =~ s|_lang_|<b>Language</b>|ig;
					$trh =~ s|_days_|<b>Days</b>|ig;
					$trh =~ s|_target_|<b>Target</b>|ig;
					$trh =~ s|_power_|<b>Power (kW)</b>|ig;
					$theTable .= $trh;

					$tnum = 0;
					$color = 0;
					foreach $stationRec (sort mySort (@foundItems)) {
						my ($tRow) = $tt;
						my ($freq,$utcTime,$station,$days,$lang,$country,$target,$power) = split(/\t/, $stationRec);
						$tnum++;
						if ($color == 0) {
							$tRow =~ s|<tr>|<tr bgcolor\=\"\#E8E8E8\">|ig;
							$tRow =~ s|<td>|<td bgcolor\=\"\#E8E8E8\">|ig;
							$color = 1;
						} else {
							$color = 0;
						}
						$utcTime =~ m|^(\d{4})[^\d]*(\d{4})$|imsg;
						my ($startTime_) = $1;
						my ($endTime_)   = $2;
						#print STDERR "st_ = [$startTime_], et_ = [$endTime_]\n";

						if (
							(($showTime >= $startTime_) && ($showTime <= $endTime_)) 
							|| (($showTime >= $startTime_) && (($endTime_ < $startTime_) && ($endTime_ < $showTime))) 
							|| (($startTime_ > $endTime_) && ($endTime_ > $showTime))
							) {
							$freq    = "<b>$freq</b>";
							$utcTime = "<b>$utcTime</b>";
							$station = "<b>$station</b>";
							$country = "<b>$country</b>";
							$lang    = "<b>$lang</b>";
							$days    = "<b>$days</b>";
							$tRow    =~ s|<tr.*?>|<tr bgcolor\=\"\#F0F4A6\">|ig;
							$tRow    =~ s|<td.*?>|<td bgcolor\=\"\#F0F4A6\">|ig;
						}
						$tRow =~ s|_freq_|$freq|ig;
						$tRow =~ s|_time_|$utcTime|ig;
						$tRow =~ s|_station_|$station|ig;
						$tRow =~ s|_country_|$country|ig;
						$tRow =~ s|_lang_|$lang|ig;
						$tRow =~ s|_days_|$days|ig;
						$tRow =~ s|_target_|$target|ig;
						$tRow =~ s|_power_|$power|ig;
						$theTable .= $tRow;
						if ($downloadOK) {
							my ($newFreqL) = $freq;
							my ($newStation) = $station;
							$newFreqL =~ s|\.||g;
							$newFreqL =~ s|\<b\>||g;
							$newFreqL =~ s|\</b\>||g;
							$newFreqL =~ s|^(\d+?)(\d\d\d)(\d\d)$|$1\.$2|;
							$newStation =~ s|\<b\>||g;
							$newStation =~ s|\</b\>||g;
							$downloadList{$newFreqL} = "$newStation\t$newFreqL\tAM\t\t";
						}
					}
					if ($downloadOK) {
						my ($rte_time) = `date -u +\"%Y-%d-%m_%H%M\"`;
						chop ($rte_time);
						my ($pid) = $$;
						my ($dlFileName) = "search_results" . "." . $pid . ".frq";
						$theTable .= "<tr><td colspan=6><br><a href=\"http://hfradio.org/hfstation/$dlFileName\">Shift-Click here to Download ";
						$theTable .= "Results for YPLog</a></td></tr>\n";
						open (OUTSF, "> /hfradio/html/hfstation/$dlFileName");
						foreach $sfreq (sort mySort keys (%downloadList)) {
							print OUTSF "$downloadList{$sfreq}\n";
						}
						close (OUTSF);
					}
					$theTable .= "</table></td></tr></table></div>\n";
				} else {
					$theTable = "<b>Nothing found for $theSearch</b><br><blockquote>Try Station names, like, Voice of America, or WHRI, etc.<br>Searches like USA are too broad.  Or, like RFI, use France.  Try alternatives.</blockquote>\n";
				}
				&showForm(2);
			}
		}
	}
}

sub showForm {
	my ($option) = @_;
	my $what = "";
	my $lastSearch = "<b>Last Five Searched:</b><br>\n";
	
	print $html_header;

	`tail -n 5 $theLogFile > $theLogFile.2.last`;
	open (RLOG, "$theLogFile.2.last");
	while (<RLOG>) {
		my $rLine = $_;
		if (m|Search\:\s+(.*)|i) {
			$what = $1;
			$lastSearch .= "$what<br>\n";
		}
	}
	close (RLOG);

	open (STYLE, "$styleSheet") || die "Could not read $styleSheet: $!\n";
	$_style = "";
	while (<STYLE>) {
		$_style .= $_;
	}
	close (STYLE);

	open (MENU, "$theMenu") || die "Could not read $theMenu: $!\n";
	$_menu = "";
	while (<MENU>) {
		$_menu .= $_;
	}
	close (MENU);

	if ($option == 1) {

		$templateFile = $templateDir . "/_hfstation1.tpl";
		$htmlTemplate = &getTemplateHTML($templateFile);
		$_title = "Search for SWL Broadcasters at HFRadio.org";
		$htmlTemplate =~ s|_TITLE_|$_title|imsg;
		$htmlTemplate =~ s|_STYLE_|$_style|imsg;
		$htmlTemplate =~ s|_NAVMENU_|$_menu|imsg;
		$htmlTemplate =~ s|_PROPAGATION_|$solarReport|imsg;
		$htmlTemplate =~ s|_LASTSEARCH_|$lastSearch|imsg;
		$htmlTemplate =~ s|_LINKS_|$theLinks|imsg;
		
		print $htmlTemplate;

	} else {
		if (length($theSearch)) {
			open (LOG, ">>$theLogFile");
			print LOG "[$gmtDay $gmtTime] Search: $theSearch\n";
			close (LOG);
		}
		$templateFile = $templateDir . "/_hfstation2.tpl";
		$htmlTemplate = &getTemplateHTML($templateFile);

		$_title = "Search Results for SWL Broadcasters at HFRadio.org";
		$htmlTemplate =~ s|_TITLE_|$_title|imsg;
		$htmlTemplate =~ s|_STYLE_|$_style|imsg;
		$htmlTemplate =~ s|_NAVMENU_|$_menu|imsg;
		$htmlTemplate =~ s|_PROPAGATION_|$solarReport|imsg;
		$htmlTemplate =~ s|_LASTSEARCH_|$lastSearch|imsg;
		$htmlTemplate =~ s|_LINKS_|$theLinks|imsg;
		$htmlTemplate =~ s|_GMTTIME_|$showTime|imsg;
		$htmlTemplate =~ s|_SEARCHFOR_|$theSearch|imsg;
		$htmlTemplate =~ s|_LANGUAGE_|$field{'lang'}|imsg;
		$htmlTemplate =~ s|_THETABLE_|$theTable|imsg;
		
		print $htmlTemplate;
	}
}

sub GetFormInput {

	(*fval) = @_ if @_ ;

	local ($buf);
	if ($ENV{'REQUEST_METHOD'} eq 'POST') {
		read(STDIN,$buf,$ENV{'CONTENT_LENGTH'});
	}
	else {
		$buf=$ENV{'QUERY_STRING'};
	}
	if ($buf eq "") {
			return 0 ;
		}
	else {
 		@fval=split(/&/,$buf);
		foreach $i (0 .. $#fval){
			($name,$val)=split (/=/,$fval[$i],2);
			$val=~tr/+/ /;
			$val=~ s/%(..)/pack("c",hex($1))/ge;
			$name=~tr/+/ /;
			$name=~ s/%(..)/pack("c",hex($1))/ge;

			if (!defined($field{$name})) {
				$field{$name}=$val;
			}
			else {
				$field{$name} .= ",$val";
			}


		   }
		}
return 1;
}

sub mySort {

	$a <=> $b;
}

sub doSolarData {

	$solarReport = "";

	$solarReport = "<small>| Current Solar Flux: <b>";
	open (PIN, "/hfradio/html/prop/.flux.txt");
	my ($line) = "";
	while (<PIN>) {
		$line = $_;
		$line =~ tr/\n\r\t//d;
		$solarReport .= $line;
	};
	close(PIN);
	$solarReport .= "</b> |<br>\n| A-index: <b>";
	open (PIN, "/hfradio/html/prop/.aindex.txt");
	while (<PIN>) {
		$line = $_;
		$line =~ tr/\n\r\t//d;
		$solarReport .= $line;
	};
	close(PIN);
	$solarReport .= "</b> | K-index: <b>";
	open (PIN, "/hfradio/html/prop/.kindex.txt");
	while (<PIN>) {
		$line = $_;
		$line =~ tr/\n\r\t//d;
		$solarReport .= $line;
	};
	close(PIN);
	$solarReport .= "</b> | Aurora: <b>";
	open (PIN, "/hfradio/html/prop/.aurora_level.txt");
	while (<PIN>) {
		$line = $_;
		$line =~ tr/\n\r\t//d;
		$solarReport .= $line;
	};
	close(PIN);
	$solarReport .= "</b> | <a href=\"http://hfradio.org/propagation.html\">more...</a> |</small>\n";

}

sub getTemplateHTML {
	my ($tFile) = @_;
	my $tLines = "";
	open (TIN, "$tFile") || die "Could not read $tFile : $!\n";
	while (<TIN>) {
		$tLines .= $_;
	}
	close (TIN);
	$tLines;
}

1;
