#!/usr/bin/perl -w

use strict;

my @filters;
my @commands;
my @counters;
my $index;

# backward compatibility for streamfilter.c
my $old_triggers=1;
while ( @ARGV ) {
  $filters[@filters]= shift @ARGV;
  $commands[@commands]="do_things $old_triggers " . '$count';
  $counters[@counters]=0;
  $old_triggers++;
}

while ( <STDIN> ) {

  # Is it a new thing to look for?
  if (/^WATCH_FOR MAGICWORD_DEADBEEFC001/) {
    chomp;
    my ($junk, $trigger, $action);
    # Split the string up -- the pattern will always be in "'s, and any
    # internal quotes will be escaped
    ($junk, $trigger, $action) = split (/(?=[^\\])\"/,$_,3);
    # Look for the old pattern (to replace it)
    for ($index=0; $index < @filters; $index++ ) {
      if ( $filters[$index] eq $trigger ) {
        last;
      }
    }
    $filters[$index]=$trigger;
    $commands[$index]=$action;
    $counters[$index]=0;

  } else {
    # Now loop through all the things we're looking for
    my $command;
    for ($index=0; $index < @filters; $index++ ) {
      if (/$filters[$index]/) {
        $counters[$index]++;
        ($command = $commands[$index]) =~ s/\$count/$counters[$index]/g;
        if( fork() == 0) {
          exec $command;
        }
      }
    }

    print "$_";
  }
}
