#!/usr/bin/perl
use warnings;
use strict;
use autodie;

use DBI;
use IO::Select;
use POSIX qw(strftime);
use Data::Dump qw(dump);

$|=1;

my $filter = 'bakaceva';
$filter = $ARGV[0] if @ARGV;

my $alert_config = "alert-$filter.txt";
die "no $alert_config config" unless -e $alert_config;

my $pn2name;
open(my $n, '<', 'subvision-numbers.txt');
while(<$n>) {
	chomp;
	my ( $number, $pn, $imei, $name ) = split(/ /,$_);
	next if $name !~ m/$filter/;
	$pn2name->{$pn} = $number;
}

sub ts {
	strftime("%Y-%m-%d %H:%M:%S ", localtime(time()));
}

my $dbh = DBI->connect("dbi:Pg:dbname=zc","dpavlin","", { RaiseError => 1, AutoCommit => 1 });

$dbh->do("LISTEN zc");
print ts,"LISTEN zc for $filter ", join(' ', keys %$pn2name), "\n";


my $fd = $dbh->func("getfd");
my $sel = IO::Select->new($fd);

my $sth = $dbh->prepare( "select * from sub_$filter where pn = ? order by time desc limit 1" );


while (1) {
	$sel->can_read;
	my $notify = $dbh->func("pg_notifies");
	if ($notify) {
		#warn "# notify = ",dump($notify);
		my ($relname, $pid, $payload) = @$notify;
		#print ts,"$relname from PID $pid $payload\n";
		my ($pn, $_id) = split(/,/, $payload);
		if ( exists $pn2name->{$pn} ) {
			$sth->execute($pn);
			my $row = $sth->fetchrow_hashref;
			#warn "# row = ",dump($row);
			# FIXME hard-coded 0.1
			if ( abs( $row->{x_axis_angle} ) > 0.1 || abs( $row->{y_axis_angle} ) > 0.1 ) {
				if ( ! -e "alert/$pn" ) {
					print ts,"ALERT $pn\n";

					open(my $fh, '>', "alert/$pn");
					print $fh dump($row);
					close($fh);

					# send sms
					my ( undef, $time ) = split(/ /,$row->{time});
					$time =~ s{\..+$}{}; # remove decimal time
					my $name = $pn2name->{$pn};

					open(my $cfg, '<', $alert_config);
					my $msg = <$cfg>;
					chomp($msg);
					$msg =~ s/\Q{{name}}\E/$name/g;
					$msg =~ s/\Q{{time}}\E/$time/g;
					print ts,"$msg\n";

					# consume email <email> number
					while(<$cfg>) {
						chomp;
						my $email = $_;
						my $number = $1 if $email =~ s{\s+(?:\+385|0)([0-9]+)$}{};
						$number = '+385' . $number;

						print ts,"ALERT $email\n";

						open(my $s, '|-', '/usr/sbin/sendmail -t');
						print $s "From: Senzori Alert <alert\@senzori.subvision.hr>\nTo: $email\nSubject: alert $name $time\n\n$msg\n\n" . dump($row) . "\n.\n";
						close($s);

						my $cmd = "ssh -p 22022 -i /home/dpavlin/.ssh/sendsms_rsa asterisk\@192.168.200.240 $number $msg";
						print ts,"## $cmd\n";
						system $cmd;
					}
				} else {
					print ts,"SKIP ALERT $pn already sent\n";
				}
			}
		}
	}
}

