#!/usr/local/bin/perl
#################################################################
#
# + FtpLocate - FTP search engine
#
# by Distributed System Lab E.E. NCKU Taiwan 2000
# http://ftp.ee.ncku.edu.tw/ftplocate/
#
#################################################################

if ( defined($ENV{'REMOTE_ADDR'}) ) { exit; }	# cgi not allowed

use CGI;
unshift(@INC, substr($0, 0, rindex($0,'/')) ); # add prog path to INC
require ("config");

############################# subs ##############################

sub train {
  my ($client,$query)=@_;
  my ($query_raw, $resultfname);

  $query=clean_str($query); 
  $query_raw=CGI::escape($query);
  $resultfname=$query_raw;

  if ( $query!~m![/\w\d\.\+\-\\_~]{2}! ) {	# keyword to short
    return 0;
  } elsif ( -f "$CACHEDIR/$resultfname" ) {	# cache hit
    return 2;
  } else {					# cache miss
    do_flsearch($client, $query, "", $resultfname);
    return 1;
  }
}

############################# main ##############################

$client=my_fqdn();
open (LOG, ">>$SYSTEMLOG");
select(LOG); $| = 1; 	# unbuffer mode
select(stdout); $|=1;	# unbuffer mode

if ( -f "$FTPLOCATEDIR/flindex.pl.RUNNING" ) {
  print timestr()." fltrain - flindex is running, abort!\n";
  print LOG timestr()." fltrain - flindex is running, abort!\n";
  exit 1;
}

@status=("canceled", "cache miss", "cache hit");
$i=0;
while ( <> ) {
  chop;
  $query=clean_str($_);
  if ( $query eq "" ) {
    last;
  }

  print timestr()." fltrain - query='$query' start\n";
  print LOG timestr()." fltrain - query='$query' start\n";
  
  $starttime=gettimeofday(); 
  $n=train($client,$query);
  $diff=int((gettimeofday()-$starttime)*100+0.5)/100;
  $totaldiff=$totaldiff+$diff;
  $i++;

  print timestr()." fltrain - query='$query' $status[$n] ($diff secs)\n";
  print LOG timestr()." fltrain - query='$query' $status[$n] ($diff secs)\n";
}

if ( $i>0 ) {
  $av=int($totaldiff/$i*100+0.5)/100;
  print timestr()." fltrain - done. $i queries in $totaldiff secs, av=$av secs\n";
  print LOG timestr()." fltrain - done. $i queries in $totaldiff secs, av=$av secs\n";
}
close(LOG);
