#!/usr/bin/perl

use DBI;

$0=~m#[^/]+$#;
$cmdpath=$`;
if ($cmdpath eq "") { $cmdpath="./"; }

unshift(@INC,$cmdpath."lib");
require "property.pl";
require "log.pl";

### configure here

$config_file=$cmdpath."smsreceiver.config";

### no configuration beyond this line

$props=&Property::read($config_file);

### connect logfile

tie *LOGFILE, 'Logfile', $$props{'public'}{'logfile'}, 'SMSRECEIVER';

print LOGFILE "Connecting to ".$$props{'db'}{'dsn'}." as user ".$$props{'db'}{'user'}."\n";


### connect to db
$dbh=DBI->connect($$props{'db'}{'dsn'},$$props{'db'}{'user'},$$props{'db'}{'passwd'});
if (!defined $dbh) {
	print LOGFILE "Error while connecting DB\n";
	exit(0);
	}
$table=$$props{'mail'}{'table'};	

### prepare
$mo_insert_q="insert into $table (produced,type_sms,message,created) values (?,?,?,NOW())";
$mo_insert_sth=$dbh->prepare($mo_insert_q);

$headermode=1;
while (<>) {
	if($headermode==1) {
		if (/^Subject: (.*)/i) {
			$subject=$1;
			}
		if (/^From: (.*)/i) {
			$from = $1;
			}
		if (/^Content-type:\s+(.*)/i) {
			$content_type=$1;
			}
		if (/^$/) {
	 	 	$headermode=0;
			}	      
    }
	else {
	  push(@contentdata,$_);
	}
}

### filter out mime-crap

if ((defined $content_type)&&($content_type!~m#^text/plain#i)) {
	print LOGFILE "Got mime-mail: $from ($subject) ".localtime(time)."\n";
	print LOGFILE "Content: ".join('',@contentdata)."\n";
	exit();
	}

### try to identify sms

if ($from=~/^\+?\d+\@/) {
	### coming from an emailaccount with a telefon number as user-part in From:
	
	### sms is in first line of body
	$text=shift(@contentdata);
	
	$type=1;
	}
else {
	$text=join('',@contentdata);
	$type=2;
	}

print LOGFILE "$type: $text\n";
$mo_insert_sth->execute(0,$type,$text);
