#!/usr/bin/perl
use strict;
#use warnings;
# turned off otherwise journal is full of noise
use v5.10;
my @fields;
my $itemval;
my $key;

open(INPUT, "/usr/bin/python3 -u /usr/local/bin/pms5003-all.py |")   || die "couldn't start outpipe: $!";
# python3 -u to disable buffering
open(OUTPUT, "| zabbix_sender -i - -c /etc/zabbix/zabbix_agentd.conf -s dusty -r > /dev/null")      || die "couldn't start inpipe: $!";
# zabbix_sender is verbose by default
OUTPUT->autoflush(1);

while (my $row = <INPUT>) {
     #say time();
     $row =~ s/^$//g;
     @fields = split /:/, $row;
     $key = $fields[0];
     for ($key) {
          # Substitute the outputs of pms5003 to Zabbix items
          s/PM1\.0.+ultrafine.+/pms5003.pm1/g;
          s/PM2\.5.+combust.+/pms5003.pm2_5/g;
          s/PM10.+dust,.+/pms5003.pm10/g;
          s/>0\.3um.+/pms5003.gt0_3um/g;
          s/>0\.5um.+/pms5003.gt0_5um/g;
          s/>1\.0um.+/pms5003.gt1um/g;
          s/>2\.5um.+/pms5003.gt2_5um/g;
          s/>5\.0um.+/pms5003.gt5_0um/g;
          s/>10um.+/pms5003.gt10um/g;  
     }
    
     $itemval = $fields[1];
     # strip all the extraneous whitespace
     $itemval =~ s/\s//g;
     # Only print those that have matched a substitution above
     unless (index($key, "pms5003")) {
        # timestamped
        #say OUTPUT  " - " . $key . " " . time() . " " . $itemval;
        # not timestamped
        say OUTPUT  " - " . $key .  " " . $itemval;
        }
}

close(INPUT);
close(OUTPUT);
