#!/usr/bin/perl 


use strict;	
use warnings FATAL=>"all";

if($>){
  exec { "/path-to-wrapper-program" }
       ( "/path-to-wrapper-program",$0,@ARGV);
}

use Socket;
use DBI;
use Date::Parse;
use POSIX q/strftime/;
use POSIX qw/strftime/;
use Time::HiRes q/gettimeofday/;


my $username = "i3d";
my $password = "password";
my $dsn = "dbi:mysql:cvs:127.0.0.1";
my $dbh = DBI->connect($dsn,$username,$password) or die "Cannot connect to database: $DBI::errstr";


my $proto = getprotobyname('udp');
my $port = 501; 

my $servaddr = sockaddr_in($port, INADDR_ANY);

socket SERVER, PF_INET, SOCK_DGRAM, $proto or die "Unable to create socket: $!";

bind SERVER, $servaddr or die "Unable to bind: $!";

print "Server running on port $port...\n";


my $message;
my $astr;
my $new_astr;
my $post;
my $queue_no;
my $counter_no;

while (my $client = recv SERVER, $message, 1024, 0) {
    my ($port, $ip) = unpack_sockaddr_in($client);
#    my $host = gethostbyaddr($ip, AF_INET);
#    print "Client $host:$port sent '$message' at ", scalar(localtime), "\n";
#    send SERVER, "Message '$message' received", 0, $client;
   
    
	#EVENT 9 1 *956 5,1
	 $astr = $message;
	 $astr=~s/ //g;
	 $astr=~s/EVENT91*//g;
	 $new_astr=$astr;
	
	 $post = index($new_astr, ",");
	 if ($post>0) {
	
		my $datetime = strftime "%Y-%m-%d %H:%M:%S ", localtime;

		$queue_no = substr($new_astr,$post);
		$queue_no=~s/,//g;
		$counter_no = $new_astr;
		$counter_no =~s/$queue_no//g; 
		$counter_no =~s/,//g;
		$counter_no = substr($counter_no,1);
    	my $sth = $dbh->prepare("INSERT INTO receiver_string (queue, counter, status, date_created, date_modified) 
							VALUES (
							'".$counter_no."',
							'".$queue_no."',
							'0',
							'".$datetime."',
							'".$datetime."')");

		$sth->execute() or die "Cannot execute sth: $DBI::errstr";

		my $sth_log = $dbh->prepare("INSERT INTO receiver_log (input_data, date_created, date_modified) 
							VALUES (
							
							'".$message."',
							'".$datetime."',
							'".$datetime."')");

		$sth_log->execute() or die "Cannot execute sth_log: $DBI::errstr";


		my $log = $dbh->prepare("INSERT INTO receiver_string_log (queue, counter, status, date_created, date_modified) 
							VALUES (
							
							'".$counter_no."',
							'".$queue_no."',
							'0',
							'".$datetime."',
							'".$datetime."')");

		$log->execute() or die "Cannot execute log: $DBI::errstr";
    }
}


