#!/usr/bin/perl
#
use strict;
use warnings;
use FindBin;
use LWP::UserAgent;
use HTTP::Request::Common qw{ POST };

# USERSIDE MODULE :: ASTERISK CONTROLLER
# REVISION: 18

my $zpath = $FindBin::RealBin;
require($zpath."/usm_asterisk.conf");

my $pidfile = "$zpath/usm_asterisk.pid";

if ( ! -e $pidfile) {
    open(my $f, '>', $pidfile);
    close($f);
};

my $running = `ps ax | grep asterisk | grep -cf $pidfile`;
if ($running == 0) {
    loger('The Asterisk module is not found in the memory. Trying to start...');
    system( 'perl '.$zpath.'/usm_asterisk.pl &' );
} else {
    send_heartbeat();
}

sub send_heartbeat {
    my $data = {
        'api'    => our $zusapikey,
        'cat'    => 'module',
        'subcat' => 'heartbeat',
        'module' => 'usm_asterisk'
    };
    $ENV{PERL_LWP_SSL_VERIFY_HOSTNAME} = 0;
    my $ua = LWP::UserAgent->new();
    my $response = $ua->post( our $zusapiurl, $data );
    my $content = $response->decoded_content();
}

sub loger {
    my $text = $_[0];
    open (LOG, '>>' . our $ps_logpath . '/usm_asterisk.log');
    print LOG now() . " [CONTROL] : " . $text . "\n";            # Вывод в логфайл
    close LOG;
}

sub now {
    my ($lsec,$lmin,$lhour,$lmday,$lmon,$lyear) = localtime(time);
    my $datetime = sprintf("%04d",($lyear+1900))."-".sprintf("%02d",($lmon+1))."-".sprintf("%02d",$lmday)." ".sprintf("%02d",$lhour).":".sprintf("%02d",$lmin).":".sprintf("%02d",$lsec);
    return $datetime;
}