#!/usr/bin/perl
#-------------------------------------------------------------------------#
# This script acts as a phone call service.  It listens on a socket for   #
# requests to make a phone call.  It also keeps track of the last time    #
# a phone call was attempted, and only attempts new requests if 30 minutes#
# have passed since the last attempt.                                     #
#-------------------------------------------------------------------------#
use IO::Socket;
use Modem::Vgetty;
$lastcall = ();
$|=1;


#--------------------------------------------------------------------------#
# create the socket                                                        #
#--------------------------------------------------------------------------#
unlink "/tmp/mysock";
$server = IO::Socket::UNIX->new(Local     => "/tmp/mysock",
                                Type      => SOCK_STREAM,
                                Listen    => 0 )
    or die $@;


#--------------------------------------------------------------------------#
# make the socket world writeable.  This allows the nagiosuser(call client)#
# to write to the socket                                                   #
#--------------------------------------------------------------------------#
`chmod 777 /tmp/mysock`;


#--------------------------------------------------------------------------#
# wait for a connection                                                    #
#--------------------------------------------------------------------------#
while ($client = $server->accept())
{
  $request = <$client>;
  if (($request =~ /call/) && (time > ($lastcall + 1700)))
  {
    $lastcall = time;
    #----------------------------------------------------------------------#
    # reset the modem before attempting to place a call                    #
    #----------------------------------------------------------------------#
    `echo "ATZ" > /dev/ttyS0`;
    sleep(10);
    `/usr/bin/killall vgetty`;
    sleep(10);
    connected ( );
  }
}

#--------------------------------------------------------------------------#
# place the phone call                                                     #
#--------------------------------------------------------------------------#
sub connected
{
  `/usr/local/bin/vm shell -l ttyS0 -S 
/usr/local/nagios/libexec/TAS/buster_alert.pl`;
}
