#!/usr/bin/perl -w
#
# sms.alert - send an alert via smstools available at
#             http://www.isis.de/~s.frings/smstools/
#
# based on qpage.alert and mail.alert by Jim Trocki, trockij@transmeta.com
#
# usage:
# 	sms.alter [flags...] -g group -s system 385abxxxxxx|name[ 12345|name...]
#
# flags which are standard:
#
# 	-u	this is upalert
# 	-g grp	group
# 	-s sys	system
# 	-l time	time to next alert
#
# flags specific to sms.alert: (all optional)
#
# 	-f	send flash sms (directly to screen)
# 	-x	send extended message (all output, smstools with split it in
# 		multiple smses if needed)
# 	-i hh:mm-hh:mm	send sms only if it falls in this interval
#
# it users file /usr/local/etc/sms.addressbook as addressbook in format
# 
# 123456	name
#
# where 123456 is phone number (with country prefix, but without +) and
# name is alias used like:
#
# sms.alert -f dobrica
#
# in mon.cf

my $sms_outgoing = "/var/spool/sms/outgoing";
my $sms_addressbook = "/usr/local/etc/sms.addressbook";

use strict;
my %opt;
use Getopt::Std;
getopts ("S:s:g:h:t:l:ufi:", \%opt);

# read addressbook
my %name2phone;
if (open(A, $sms_addressbook)) {
	while(<A>) {
		chomp;
		next if (/^[#;]/);
		my ($phone,$name) = split(/\s+/,$_,2);
		$name2phone{lc($name)} = $phone;
	}
}

#
# the first line is summary information, adequate to send to a pager
# or email subject line
#
#
# the following lines normally contain more detailed information,
# but this is monitor-dependent
#
my @MSG=<STDIN>;
my $summary = shift @MSG;
chomp $summary;

if ($opt{i}) {
	if ($opt{i} =~ /(\d+):(\d+)-(\d+):(\d+)/) {
		my $from = $1 * 60 + $2;
		my $to = $3 * 60 + $4;
		my ($sec,$min,$hour) = localtime(time);
		my $t = $hour * 60 + $min;
		exit 0 if ($t < $from || $t > $to);
	} else {
		die "interval time format: hh:mm-hh:mm"
	}
}

$summary = $opt{S} if $opt{S};

my ($wday,$mon,$day,$tm) = split (/\s+/, localtime);

my $ALERT = $opt{u} ? "UPALERT" : "ALERT";

my $sms = "From: mon\n";
$sms .= "Flash: yes\n" if $opt{f};
$sms .= "\n$ALERT";
$sms .= " $opt{g}/$opt{s}" if ($opt{g} && $opt{s});
$sms .= " $summary ($wday $mon $day $tm)\n";
# add next alter time
$sms .= "Secs until next alert: $opt{l}\n" if $opt{l};
# add rest of text
$sms .= join("\n",@MSG) if $opt{x};

my $suffix = 0;

foreach my $to (@ARGV) {
	if (open(SMS, "> $sms_outgoing/mon-$$-$suffix")) {
		my $phone = $to;
		$phone = $name2phone{lc($to)} if ($name2phone{lc($to)});
		die "$phone is not phone number! " if ($phone !~ m/^\d+$/);
		print SMS "To: $phone\n$sms";
		close SMS;
		$suffix++;
	} else {
		die "could not open sms file in '$sms_outgoing': $!";
	}
}
