#!/usr/bin/perl
# Update links page
# Uses postgres table MyLinks to update links page
# Gerry Patterson, May 2002
# Downloaded from http://www.pgts.com.au/download/scripts

# db connect information goes here -- keep this secure!
$connect = "MyConnect";
$SID = "MyDB";
# NB: This string contains a TAB -- It would not recognise '\t' (undocumented feature?)
$PSQL  = "/usr/local/pgsql/bin/psql -F '	' -t -A -v ON_ERROR_STOP=1 -U $connect -d $SID";

# temp files -- clean them up with cron'ed job
chomp( $sqltmp = `mktemp /tmp/XXXXXX`);
die "Cannot create temp file: $sqltmp" unless (-f $sqltmp);
$sqlout = "$sqltmp.out";
$sqlerr = "$sqltmp.err";

# ------------------------------------------------------------------------

# run a query using the $PSQL string
sub run_sql{
	my $status;
	unlink( $sqlout,$sqlerr);
	open ( SQLTMP,">$sqltmp") || die "Error Opening temp file $sqltmp";
	# open an output channel to $sqlout
	print SQLTMP '\o ' . "$sqlout\n";
	print SQLTMP "$_[0]\n";
	close SQLTMP || die "Closing temp file $sqltmp";
	$status = system( "$PSQL -f $sqltmp 2>$sqlerr");
	if ( $status){
		open ( TMP,"$sqlerr") || die "Error opening $sqlerr";
		@t = <TMP>;
		die(@t);
	}
}

# ------------------------------------------------------------------------

# Main Procedure starts here ...

die "usage: $0 html_file\n" unless (@ARGV == 1);
run_sql "select category, link, name, description from MyLinks
	where valid order by category,name;";
open(HTML,$ARGV[0]) || die "Cannot open HTML: $ARGV[0]\n";
$links_flag = 0;
while (<HTML>){
	$links_flag++ if (/<!-- Useful Links -->/);
	if (/<!-- End Useful Links -->/){
		$links_flag = 0;
		next;
	}
	if ( $links_flag == 0 ){
		print $_;
		next;
	}
	next unless ($links_flag == 1);
	# replace text between <!-- Useful Links --> .. <!-- End Useful Links -->
	print '<!-- Useful Links -->
<table border=0 cellpadding=0 cellspacing=0>

    <tr>
      <td valign=top width=100>
        <font size=+1><b>Category</b></font>
      </td>
      <td valign=top>
        <font size=+1><b>Link</b></font>
      </td>
      <td width=10></td>
      <td width=470 valign=top>
        <font size=+1><b>Description</b></font>
      </td>
    </tr>

';
	open ( SQLTMP,"$sqlout") || die "Error Opening input file $sqlout";
	while ( <SQLTMP> ){
		chomp;
		my @w = split ( /\t/,$_);
		unless ( $w[0] eq $category){
			$category = "$w[0]";
			print "    <tr><td colspan=4 height=10></td></tr>\n";
			print "    <tr><td colspan=4><b>$category" . ":</b></td></tr>\n";
		}
		print '    <tr><td colspan=4 height=3></td></tr>
    <tr>
      <td valign=top></td>
      <td valign=top>
        <a href="http://' . $w[1] . '">' . $w[2] . '</a>
      </td>
      <td width=10></td>
      <td valign=top>
        ' . $w[3] . '
      </td>
    </tr>

';
	}
	print '</table>
<!-- End Useful Links -->
';
	$links_flag++;
}
