#!/usr/bin/perl

$MAXHITS=30;

@months=('','January','February','March','April','May','June','July','August','September','October','November','December');

print "Content-type: text/html\n\n";

my $repeatquery;
my @parts=split(/&/,$ENV{'QUERY_STRING'});
foreach $part(@parts) {
 my ($name,$value)=split(/=/,$part);
 if ($name eq 'q') {$repeatquery=$value;}
 $value=~tr/+/ /;
 $value=~s/%([0-9a-fA-F][0-9a-fA-F])/pack("C",hex($1))/eg;
 $value=~s/\&/\&amp\;/g;
 $value=~s/\</\&lt\;/g;
 $value=~s/\>/\&gt\;/g;
 $QUERY{$name}=$value;
}

my ($header,$footer);
{
 my $old=$/;
 undef $/;
 open(HANDLE,'../blog/header.html');
 $header=<HANDLE>;
 close(HANDLE);
 $header=~s/<!--#echo var="QUERY_STRING" -->/Search/sg;
 $header=~s/<!--.*?-->//sg;
 print $header;
 open(HANDLE,'../blog/archivelinks.html');
 $footer="</DIV>\n".<HANDLE>."</BODY>\n</HTML>";
 close(HANDLE);
 $/=$old;
}

my $qry=$QUERY{'q'};
$qry=~s/"/\&quot\;/g;
print '<FORM ACTION="/cgi-bin/search.pl" METHOD="GET"><TABLE BORDER="0"><TR><TD>
Search:</TD><TD><INPUT TYPE="TEXT" NAME="q" VALUE="'.$qry.'"></TD><TD><INPUT CLASS="button" TYPE="SUBMIT" VALUE="Go"></TD>
</TR></TABLE></FORM>';

my $fileindex=$#files;
my $count=0;
my $start=int($QUERY{'start'}||0);

$qry=$QUERY{'q'};
if ($qry) {
 use DBI;
 my $dbh=DBI->connect('DBI:mysql:database=blog_ravenblack_net;mysql_socket=/var/local/mysql/mysql.sock','blog','p0rky',{PrintError=>0});
 if ($dbh) {
 my $q=lc($qry);
 $q=~s/\\/\\\\/g;
 $q=~s/%/\\%/g;
 $q='%'.$q.'%';
 my $sth=$dbh->prepare('SELECT datetime,blurb FROM blog WHERE blurb LIKE ? ORDER BY datetime DESC LIMIT '.$start.',20');
 $sth->execute("$q");
 $count=$sth->rows;
 my $i=$count;
 print '<TABLE WIDTH="85%" CELLSPACING="0" CELLPADDING="0">';
 while ($i) {
  my ($datetime,$blurb)=$sth->fetchrow_array;
  my ($sec,$minute,$hour,$day,$month,$year,$wday)=localtime($datetime);
  print '<TR><TD CLASS="lump"><A HREF="/archive'.($year+1900).($month<9?'0':'').($month+1).'.html#'.$day.'">'.$day.' '.$months[$month+1].' '.($year+1900).'</A></TD>
<TD CLASS="lump">'.$blurb.' <SPAN CLASS="stamp">[<A CLASS="com" HREF="/cgi-bin/comment.pl?stamp='.$datetime.'">comments</A>]</SPAN></TD></TR>';
  $i--;
 }
 print "</TABLE>\n";
 $dbh->disconnect;
 } else {
  print "<H1>Database is currently down.</H1>";
 }
}

print '</DIV><DIV ALIGN="CENTER">';
if ($count==0) {$qry=~s/\\(.)/$1/g; print "<BR>No matches found for $qry.";}
elsif ($count==20) {print '<BR><A HREF="search.pl?q='.$repeatquery.'&amp;start='.($start+20).'">Next 20</A>';}
else {print "<BR>$count matches found.";}
print "<BR><BR>\n";

print $footer;


sub PrintMatchDate {
 my ($date,$file)=@_;
 print '<BR><A HREF="/'.$file.'#'.substr($date,6,2).'">';
 print substr($date,6,2).' '.$months[substr($date,4,2)].' '.substr($date,0,4);
 print ': ';
}
