#!/usr/bin/perl -w

$DBHOST='localhost';
$DBNAME='crossspider';
$DBAUTHUSER='robot';
$DBAUTHPW='01001';

$CLUSTERCMD='netcat localhost 41112';
$CLUSTERUSER='r0bot';
$CLUSTERPW='01001';


#------ END of settings -------------


# create table lines(id serial, stamp timestamp with time zone, call text, qrg numeric(10,1), spot text);
# grant all on lines TO robot;
# grant all on lines_id_seq TO robot;

use IPC::Open2;
use DBI;
use POSIX;

sub qs{
  my($s)=@_;
  
  if (!defined($s)) {return undef;}
  $s=~s/'/''/g;
  $s=~s/\\/\\\\/g;
  return $s;
}

sub db_exec{
  my ($query) = @_;
  my($q) = $db->prepare($query) or die $db->errstr;
  $q->execute();
  return $q;
}


$db=DBI->connect("DBI:Pg:".
                 "dbname=$DBNAME;host=$DBHOST;",
               $DBAUTHUSER,
               $DBAUTHPW) or die "Can't connect to database: ".DBI->errstr."\n";

open2(\*RFD,\*WFD, $CLUSTERCMD) or die;
sleep(1);
print WFD $CLUSTERUSER."\n"; 
print WFD $CLUSTERPW."\n"; 

print WFD "set/nohere\n"; 
while($s=<RFD>){
    $s=~s/[\r\n]+//;
    print "$s\n";
    $call='';
    $qrg=0;
    if ($s=~/^DX de /){
        #print "robot $s\n";
        $call=substr($s, 26, 13);
        $call=~s/\s+//g;
        $qrg=substr($s, 15, 9);
        print "call='$call' qrg='$qrg'\n";
    }
        
    db_exec("insert into lines(stamp, call, qrg, spot) values(now(), '".qs($call)."','".qs($qrg)."','".qs(substr($s, 0, 80))."')");
    
}
close(RFD);
close(WFD);

