#!/usr/bin/perl
use DBI;
use strict;

$SIG{INT} = \&hangUp;
$SIG{HUP} = \&hangUp;
$SIG{TERM}= \&hangUp;

my $killall = "/usr/bin/killall";
my $pidFile = "/var/run/dial-in.pid";
my $timeFile= "/var/run/dial-in.stime";
my $rm = "/bin/rm";
my $stime = time();
my $dur;
my $inb;
my $outb;
my $db;
my $q;
my $query;

open PID, ">$pidFile";print PID "$$";close PID;
open RT, ">$timeFile";print RT "$stime";close RT;

$db = DBI->connect('DBI:mysql:ppp', 'root', '');

open PPP, "/usr/sbin/pppd /dev/modem 115200 user fklama |";
while(<PPP>){;}

sub hangUp {
	system("$killall -HUP pppd");
	while(<PPP>) {
		if(/^Connect\s+time\s+(\d+\.?\d*)/){$dur=$1;}
		if(/^Sent\s+(\d+)\s+bytes,\sreceived\s+(\d+)\s+bytes\./){$outb=$1;$inb=$2;}
	}
	$query  = "INSERT INTO times SET time=$stime, duration=$dur, sent=$outb, ";
	$query .= "recived=$inb";
	$q=$db->prepare($query);
	$q->execute();
	$q->finish();
	system("$rm $pidFile");
	system("$rm $timeFile");
	exit 0;
}
