#!/usr/bin/perl

$touchfile="/tmp/MagnetometerAlertTouch";
$polltime = 45;

$errorsound="/usr/local/lib/TheSystemIsDown.mp3";
$errorvoice="Victoria";

$stdvoice="Victoria";

$speak = 1;
$playsound = 0;
$speakwords = 0;
$now = localtime(time);

while (<STDIN>) {
    chop;
    s/\'/ /g;
    s/\"/ /g;
    if ($msgbegun == 1) {
	if (/Time: (.*)/) { $sendtime=$1; }
	elsif (/Code: (.*)/) { $codelevel = $1; }
	else {
	    $a .= $_;
	    $a .= " ";
	}
    }
    elsif (/From: (.+?) /) {$from = $1; }
    elsif (/Subject: (.+)/) { $subject = $1;  }
    elsif (/To: (.+) \</) { $to = $1; }
    elsif ($_ eq "") { $msgbegun=1; } 
}

print $a;

if ($codelevel =~ /\w+/) {
    open (toucher,">$touchfile-$from");
    print toucher $codelevel;
    close (toucher);
}

$codelevelinitial=$codelevel;

if (($subject =~ /rror/)||($codelevel eq "Red")) {

    $speakvoice = $errorvoice;
    $speakwords = "Code $codelevel from $from. $subject. $a";
    $playsound = $errorsound;

}

elsif ($subject =~ /Status Code/) {
    die;
}

else {

    $speakvoice = $stdvoice;
    $speakwords = "Code $codelevel from $from. $subject. $a";
}

&Speech;

if (($codelevel ne "Red") && ($codelevel ne "Orange")) { die; }

print "\nWaiting for $polltime... ";

sleep $polltime;

&UpdateCodeLevel;

while ($codelevel eq $codelevelinitial) {

    &Speech;
    
    print "\nWaiting for $polltime... ";
    sleep $polltime;

    &UpdateCodeLevel;

}

sub UpdateCodeLevel {

     open (toucher,"<$touchfile-$from");
     while (<toucher>) { $codelevel = $_; }
     close (toucher);

     print "$codelevel\n";

 }

sub CheckMuting {
    $speak = 1;
    #if (-e $touchfile) { $speak=0; }
}

sub Speech {

    &UpdateCodeLevel;

    &CheckMuting;
    if ($speak) {

	open (toucher,">$touchfile");
	print toucher $now;
	close (toucher);

	if ($speakwords) {
	    print $speakwords; 
	    system "/usr/bin/say -v $speakvoice $speakwords";
	}

	&UpdateCodeLevel;

	if ($playsound && ($codelevel eq $codelevelinitial)) {
	    system "/sw/bin/mpg123 $playsound";
	}

	unlink $touchfile;
    }

}
