#!/usr/bin/perl

# Path to multimon
# $mm = "/usr/bin/multimon -a DTMF 2> /dev/null";
$mm = "aoss multimon -q -a DTMF";

# Tone/DTMF string to trigger on
# $on_str = "123";
$on_str = "*43";
@on_arr = split(//,"$on_str");

# Command or script to execute
# $on_cmd = "echo Fire Fire Fire | mail -s Fire you@cellphone.com";
$on_cmd = "bash run_rml_on_dtmf_trigger.sh";

select STDOUT;
$| = 1;
$l = 0;
$l = 0;
$ans = "";

sub System {
  if ((0xffff & system $args) != 0 ) {
    print STDERR "error: $!\n";
    exit 1;
  }
}

open M, "$mm |" || die "Can't open $mm: $!\n";
while (<M>) {
  ($a, $b) = split ':';
  # $b =~ tr/0-9*#ABCD//csd; # Allow 0-9 * # A B C D
  $b =~ tr/0-9*#//csd; # Allow 0-9 * # 
  $i = length $ans;
  if ($b eq $on_arr[$i]) {
    $ans .= $b;
  }
  elsif ($l ge "5")  {
    $l = 0;
    $ans = "";
  }
  $l++;
  if ((length $ans) == (length $on_str)) {
    print localtime()."\n$ans detected. Running $on_cmd\n";
    if ($ans eq $on_str) {
      System($args = $on_cmd);
      $l = 0;
      $ans = "";
    }
    else {
      $l = 0;
      $ans = "";
    }
  }
}
