#!/usr/bin/perl
#
# Action module for Ant monitoring system
#
# Sends sms with report.
# Uses gnokii package.
#
# No arguments are used.
# Input format:
#
# +CCCCNNNNNN1 +CCCCNNNNNN2 ... +CCCCNNNNNNK\n
# message here\n
# \n

use Fcntl;

$ENV{PATH}="/usr/sbin";

my $gnokii='/usr/bin/gnokii';

die "Cannot find gnokii!\n" unless -x $gnokii;

$|=1;

$,=' ';

my $line;
my %to;
my $msg;
my $p2;
my $i;

chomp @ARGV;
my $to=join(',',map {"<$_>"} @ARGV);

fcntl(STDIN,F_SETFL,fcntl(STDIN,F_GETFL,0)|O_NONBLOCK);

sub action();
sub sendit();

for(;;){
  $line='';
INNER_LOOP:
  for(;;){
    while(read(STDIN,$p,1)>0){
      $line.=$p;
      last INNER_LOOP if $p eq "\n" and $p2 eq "\n";
      $p2=$p;
    }
    select(undef,undef,undef,0.3);
  }
  action();
}

sub action( ){
  unless($line =~ /^([^\n]*)\n(.*)/s){
    warn "Incorrect input! ($line)\n";
    return;
  }
  $line=$1;
  $msg =$2;
  %to=split(/\s+/, $line);
  foreach $i (keys(%to)){
    open SMS,"|$gnokii --sendsms '$i'" or die "Cannot run gnokii!";
    print SMS $msg;
    close SMS;
  }
}
