#!/usr/bin/perl
#-------------------------------------------
# Az adatbazis kapcsolat felepitese
#-------------------------------------------
use DBI;
use IO::Handle;
use Time::Local;


#$databaseName = "DBI:Pg:dbname=ozekisms";
$databaseName = "DBI:mysql:ozekisms";
$databaseUser = "root";
$databasePw = "";

$dbh = DBI->connect($databaseName, $databaseUser, $databasePw) 
       || die "Connect failed: $DBI::errstr\n";

#-------------------------------------------
# A beekrezo SMS-ek hatasara lefut ez az eljaras
#-------------------------------------------

sub smsReceived
{
  my $sender = shift;
  my $msg = shift;
  
  system ('echo smsreceived | mail gyula.rabai@ozeki.hu'); 
}

############################################################################################################
# Ez alatt a sor alatt altalaban mar nem kell 
# semmilyen valtoztatast vegezni
############################################################################################################

if (-e "/var/sms/folders/stop_sms2sql") {unlink "/var/sms/folders/stop_sms2sql";}
#-------------------------------------------
# Logfileok megnyitasa
#-------------------------------------------
open (SQLLOG,">>/var/sms/logs/sms2sql-executed_sql") || die "Cannot open logfile logs/sms2sql-executed_sql";
SQLLOG->autoflush(1);
open (SQLERROR,">>/var/sms/logs/sms2sql-failed_sql") || die "Cannot open logfile logs/sms2sql-failed_sql";
SQLERROR->autoflush(1);

while (!(-e "/var/sms/folders/stop_sms2sql")) {
#-------------------------------------------
# A beerkezo uzenetek feldolgozasa
#-------------------------------------------
$dir = "/var/sms/folders/inbox";
opendir(INBOXDIR,"/var/sms/folders/inbox");
@dirlist = readdir(INBOXDIR);
closedir(INBOXDIR);

$failed=0;

foreach $filename (@dirlist) {
   if (!(-d $dir."/".$filename) && !($filename =~ '.*.lock$')) {
      $lockfilename = $dir."/".$filename.".lock";
      if (!(-e $lockfilename)) {
          open (SMSFILE,$dir."/".$filename);
	  @lines = <SMSFILE>;
	  close (SMSFILE);
	  $x=0;
	  foreach $line (@lines) {
	     chop($line);
	     chop($line);
	     $lines[$x++]=$line;
	  }
	  # -------------------------------
	  # Az SMS uzenet feldolgozasa
	  # -------------------------------
	  &clearFailed;
	  $msg = $lines[2];
	  $msg =~ s/\\/\\\\/;
	  $msg =~ s/'/\\'/;
	  $sql = "INSERT INTO ozekismsin (sender,receiver,msg,senttime,receivedtime) ";
	  $sql .= "VALUES ('$lines[0]','$lines[1]','$msg','$lines[4]',now());";

	  $sth=$dbh->prepare($sql) || &setFailed;
	  if (!(&isFailed)) {
	  	$res=$sth->execute || &setFailed;
		$sth->finish();
	  }

	  if (&isFailed) {
		printf(SQLERROR "SQL ERROR (".&timeStamp."): $sql\n");
	  } else {
		printf(SQLLOG "$sql\n");
	  }

          &smsReceived($lines[0],$msg);

	  # -------------------------------
	  # Ha az SMS feldolgozas sikeres, 
	  # toroljuk a file-t az inboxbol
	  # -------------------------------
	  if (!&isFailed) {
		unlink($dir."/".$filename);
	  }
      }
   }
}

#-------------------------------------------
# A kimeno uzenetek feldolgozasa
#-------------------------------------------
&clearFailed;
$sql = "SELECT sender,receiver,msg,id FROM ozekismsout WHERE status='send'";
$sth=$dbh->prepare($sql) || &setFailed;
if (!(&isFailed)) { $res=$sth->execute || &setFailed;}
if (!(&isFailed)) {
   while ($row=$sth->fetchrow_arrayref) {
       $sender = $row->[0];
       $receiver = $row->[1];
       $msg = $row->[2];
       $dbid = $row->[3];

       $fn = "/var/sms/folders/outbox/".&randomString(10);
       $fnlock = $fn.".lock";
       #Create lock file
       open(LOCK,">$fnlock") || die "SMS ERROR: cannot create lockfile";;
       close(LOCK);
       #Create sms file
       open(SMSF,">$fn") || die "SMS ERROR: cannot create outgoing sms file";
       printf(SMSF "$sender\n");
       printf(SMSF "$receiver\n");
       printf(SMSF "$msg\n");
       printf(SMSF "\n");
       printf(SMSF "\n");
       printf(SMSF "\n");
       printf(SMSF "6\n");
       printf(SMSF "\n");
       printf(SMSF "\n");
       printf(SMSF "\n");
       close(SMSF);
       unlink($fnlock);

       $sql="UPDATE ozekismsout SET status='sent' WHERE id='$dbid'";
       $upd_sth=$dbh->prepare($sql) || &setFailed;
       $upd_sth->execute || &setFailed;
       $upd_sth->finish();
   }
}


sleep(2);
} 

#-------------------------------------------
# Az adatbazis kapcsolat bontasa
#-------------------------------------------
$dbh->disconnect();
close(SQLLOG);
close(SQLERROR);
unlink "/var/sms/folders/stop_sms2sql";



#-------------------------------------------
# Fuggvenyek
#-------------------------------------------
sub clearFailed
{
   $failed = 0;
}

sub setFailed
{
   $failed = 1;
   return failed;
}

sub isFailed
{
   return $failed;
}

sub timeStamp
{
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
$mon++;
$year+=1900;
return "$year-$mon-$mday $hour:$min:$sec";
}

sub randomString {
##
## RandomString([$length, [$chars]])
##
## Returns a string of length $length containing random characters
## from the string $chars. Suggested use: password generation
##

my $length  = shift || 8;
my $chars   = shift || "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

my $s = "";
my $i = 0;
for ($i = 0; $i < $length; $i++) {
   $s .= substr($chars, int(rand(length($chars))), 1);
}
$s;
}


