#!/usr/bin/perl
# parser pentru mesajele MQTT
# Version: 1.0.1
use strict;
use warnings;
use JSON qw( decode_json );
use DBI;
use Proc::Daemon;

# pentru debug pun daemon=0 ca sa nu mai ruleze ca daemon
my $daemon=1;
my $continue;
if ($daemon==1){
  Proc::Daemon::Init;
  $continue = 1;
  $SIG{TERM} = sub { $continue = 0 };
  open PID, ">>/var/run/mqttparser.pid" or die "Couldn't open file: $!";
  print PID "$$\n";
  close PID;
}

# citesc fisierul de config
my $config = '/etc/mqttparser.conf';
open my $CFG, $config or die "Could not open my $config: my $!";

my $db;
my $dbuser;
my $dbpass;
my $dbhost;
my $mqttuser;
my $mqttpass;
my $row=1;
while( my $line = <$CFG>){
  my @credentials = split /=/, $line;
  if ($row==1) {$db = $credentials[1]; chomp($db);}
  if ($row==2) {$dbuser = $credentials[1]; chomp($dbuser);}
  if ($row==3) {$dbpass = $credentials[1]; chomp($dbpass);}
  if ($row==4) {$dbhost = $credentials[1]; chomp($dbhost);}
  if ($row==5) {$mqttuser = $credentials[1]; chomp($mqttuser);}
  if ($row==6) {$mqttpass = $credentials[1]; chomp($mqttpass);}
  $row++;
}
close $CFG;

my $dbh = DBI->connect("DBI:mysql:$db:$dbhost", $dbuser, $dbpass);
open(my $SUB, "/usr/bin/mosquitto_sub -u $mqttuser -P $mqttpass -v -t \"stat/#\" |");
while (my $mqttMessage = <$SUB> ) {
  # spargem mqttMessage in doua, dupa prima { si obtinem canalul si json-ul:
  my $channel = substr($mqttMessage, 0, index("$mqttMessage", '{'));
  my $json = substr($mqttMessage, index("$mqttMessage", '{'), -1);
  # spargem canalul: stat/esrqtsa-3434/ESP
  (my $root, my $topic, my $queue) = split /\//, $channel;
  # de obicei, exista un spatiu dupa afisarea canalului si-i fac remove
  $queue=~ s/\ //g;
  # cu mesajele care vin pe stat/+/ESP si contin in json Temp fac grafice
  if ($queue eq "ESP"){
    my $decoded = decode_json($json);
    my $temp=$decoded->{'Temp'};
    colect ($topic, 'Temp', $temp);
    my $query = "insert into mqttparser values (?, ?, ?)";
    my $sqlQuery  = $dbh->prepare($query) or die "Can't prepare $query: $dbh->errstr\n";
    $sqlQuery->execute('0', $decoded->{'Temp'}, '101');
    $sqlQuery->finish();
  }
}
$dbh->disconnect;

if ($daemon==1){
  while ($continue) {
  }
}
sub colect {
  (my $device, my $camp, my $val) = @_;
  my $cale='/admin/scripts/mqtt-perl/test.txt';
#  my $filename="test.txt";
#  if ($camp eq "Temp"){
#    $filename="temperatura.txt";
#  }
#  if ($camp eq "Humi"){
#    $filename="umiditate.txt";
#  }
  my $cale_fisier=$cale;
  open (my $fh, '>>', $cale_fisier) or die "Cannot open";
  print $fh "valoare - topic: $val - $device\n";
  close $fh;
  return;
}