#!/usr/bin/perl
use DBI;
################################################################
#
# call-logd is a part of the callid package and is written by
# M. Possamai, based on an earlier perl script by M. de Vries.
#
################################################################

$MAIN::db = "callid";
$MAIN::database_username = "callid";
$MAIN::database_password = "";
$MAIN::dsn = "DBI:mysql:$MAIN::db";


#Loop check D channel using isdntrace (i4bsd)
#isdntrace -o option disables the logfile.
#The method below reads the output from isdntrace, it's stays looping and
#waiting for a calling party number ident, when this happend the string is
#parsed and the phonenumber is split of.


open ISDNTRACE, "isdntrace -o |" or die "can't open isdntrace: $!\n";
while($DUMP = <ISDNTRACE>){
  
  @grepcpn = grep(/called party number:|calling party number:/i, $DUMP);
  $grepS = "@grepcpn";
    
      if ($grepS eq ''){
         #stay in WHILE ISDNTRACE
      }#end if

      else{
       @cpn = split(' ', $grepS);

       if ($cpn[0] eq "[calling") {
          if ($cpn[3] ne "(type=national,") {
           $phonenr = "$cpn[3]";
          }
       }
       if ($cpn[0] eq "[called") { 
          $msnnr = "$cpn[3]";
       }

           
            if ($msnnr eq ''){
              #continue
            }#end if

            else{
#              print "$phonenr is calling you on MSN nr $msnnr\n";

		# TIME&DATE
		($sec,$min,$hour,$day,$month,$year) = (localtime)[0,1,2,3,4,5];
		$year  = $year  + 1900;
		$month = $month + 1;

		$dbh = DBI->connect("$MAIN::dsn","$MAIN::database_username","$MAIN::database_password");
		$mysql = "INSERT into calls (msnnr,phonenr,timestamp) values ('$msnnr','$phonenr','$year:$month:$day:$hour:$min:$sec')";
		$dbx = $dbh->prepare($mysql);
		$dbx->execute();

              $phonenr = "";
              $msnnr = "";
	      $dbx->finish();
   $dbh->disconnect();
            }#end else

     }#end else
}#end WHILE ISDNTRACE
