#!/usr/bin/perl
#/* ========================================
# * ███╗   ███╗██████╗ ██╗ █████╗ ██╗
# * ████╗ ████║██╔══██╗██║██╔══██╗██║
# * ██╔████╔██║██║  ██║██║███████║██║
# * ██║╚██╔╝██║██║  ██║██║██╔══██║██║
# * ██║ ╚═╝ ██║██████╔╝██║██║  ██║███████╗
# * ╚═╝     ╚═╝╚═════╝ ╚═╝╚═╝  ╚═╝╚══════╝
# * ========================================
# * mDial - Omni-Channel Contact Centre Suite.
# * Initially Written by Martin McCarthy.
# * Contributions welcome.
# * Active: 2020 - 2023.
# *
# * This software is licensed under AGPLv2.
# * You can find more information here;
# * https://www.gnu.org/licenses/agpl-3.0.en.html
# * A copy of the license is also shipped with this build.
# *
# * Important note: this software is provided to you free of charge.
# * If you paid for this software, you were ripped off.
# *
# * This project is a fork of the awesome FOSS project, ViCiDial.
# * ViCiDial is copyrighted by Matt Florell and the ViCiDial Group
# * under the AGPLv2 license.
# *
# * You can find out more about ViCiDial;
# * Web: https://www.vicidial.com/
# * Email: Matt Florell <vicidial@gmail.com>
# * IRC: Libera.Chat - ##vicidial
# *
# * Bug reports, feature requests and patches welcome!
# * ======================================== */
$script = 'agi-set_variables.agi';
( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) =
  localtime(time);
$year = ( $year + 1900 );
$mon++;
if ( $mon < 10 )  { $mon  = "0$mon"; }
if ( $mday < 10 ) { $mday = "0$mday"; }
if ( $hour < 10 ) { $hour = "0$hour"; }
if ( $min < 10 )  { $min  = "0$min"; }
if ( $sec < 10 )  { $sec  = "0$sec"; }
$now_date_epoch = time();
$now_date       = "$year-$mon-$mday $hour:$min:$sec";
$PATHconf       = '/etc/astguiclient.conf';
open( conf, "$PATHconf" ) || die "can't open $PATHconf: $!\n";
@conf = <conf>;
close(conf);
$i = 0;

foreach (@conf) {
    $line = $conf[$i];
    $line =~ s/ |>|\n|\r|\t|\#.*|;.*//gi;
    if ( ( $line =~ /^PATHhome/ ) && ( $CLIhome < 1 ) ) {
        $PATHhome = $line;
        $PATHhome =~ s/.*=//gi;
    }
    if ( ( $line =~ /^PATHlogs/ ) && ( $CLIlogs < 1 ) ) {
        $PATHlogs = $line;
        $PATHlogs =~ s/.*=//gi;
    }
    if ( ( $line =~ /^PATHagi/ ) && ( $CLIagi < 1 ) ) {
        $PATHagi = $line;
        $PATHagi =~ s/.*=//gi;
    }
    if ( ( $line =~ /^PATHweb/ ) && ( $CLIweb < 1 ) ) {
        $PATHweb = $line;
        $PATHweb =~ s/.*=//gi;
    }
    if ( ( $line =~ /^PATHsounds/ ) && ( $CLIsounds < 1 ) ) {
        $PATHsounds = $line;
        $PATHsounds =~ s/.*=//gi;
    }
    if ( ( $line =~ /^PATHmonitor/ ) && ( $CLImonitor < 1 ) ) {
        $PATHmonitor = $line;
        $PATHmonitor =~ s/.*=//gi;
    }
    if ( ( $line =~ /^VARserver_ip/ ) && ( $CLIserver_ip < 1 ) ) {
        $VARserver_ip = $line;
        $VARserver_ip =~ s/.*=//gi;
    }
    if ( ( $line =~ /^VARDB_server/ ) && ( $CLIDB_server < 1 ) ) {
        $VARDB_server = $line;
        $VARDB_server =~ s/.*=//gi;
    }
    if ( ( $line =~ /^VARDB_database/ ) && ( $CLIDB_database < 1 ) ) {
        $VARDB_database = $line;
        $VARDB_database =~ s/.*=//gi;
    }
    if ( ( $line =~ /^VARDB_user/ ) && ( $CLIDB_user < 1 ) ) {
        $VARDB_user = $line;
        $VARDB_user =~ s/.*=//gi;
    }
    if ( ( $line =~ /^VARDB_pass/ ) && ( $CLIDB_pass < 1 ) ) {
        $VARDB_pass = $line;
        $VARDB_pass =~ s/.*=//gi;
    }
    if ( ( $line =~ /^VARDB_port/ ) && ( $CLIDB_port < 1 ) ) {
        $VARDB_port = $line;
        $VARDB_port =~ s/.*=//gi;
    }
    $i++;
}
if ( !$VARDB_port ) { $VARDB_port = '3306'; }
if ( !$AGILOGfile ) { $AGILOGfile = "$PATHlogs/agiout.$year-$mon-$mday"; }
use DBI;
use Asterisk::AGI;
$AGI  = new Asterisk::AGI;
$dbhA = DBI->connect( "DBI:mysql:$VARDB_database:$VARDB_server:$VARDB_port",
    "$VARDB_user", "$VARDB_pass" )
  or die "Couldn't connect to database: " . DBI->errstr;
$stmtA = "SELECT agi_output FROM servers where server_ip = '$VARserver_ip';";
$sthA  = $dbhA->prepare($stmtA) or die "preparing: ", $dbhA->errstr;
$sthA->execute or die "executing: $stmtA ", $dbhA->errstr;
$sthArows = $sthA->rows;

if ( $sthArows > 0 ) {
    $AGILOG       = '0';
    @aryA         = $sthA->fetchrow_array;
    $DBagi_output = $aryA[0];
    if ( $DBagi_output =~ /STDERR/ ) { $AGILOG = '1'; }
    if ( $DBagi_output =~ /FILE/ )   { $AGILOG = '2'; }
    if ( $DBagi_output =~ /BOTH/ )   { $AGILOG = '3'; }
}
$sthA->finish();
if ( length( $ARGV[0] ) > 1 ) {
    if ($AGILOG) { $agi_string = "Perl Environment Dump:"; &agi_output; }
    $i = 0;
    while ( $#ARGV >= $i ) {
        $args = "$args $ARGV[$i]";
        if ($AGILOG) { $agi_string = "$i|$ARGV[$i]"; &agi_output; }
        $i++;
    }
    @ARGV_vars      = split( /-----/, $ARGV[0] );
    $CLI_exten      = $ARGV_vars[0];
    $force_playback = $ARGV_vars[1];
}
$| = 1;
while (<STDIN>) {
    chomp;
    last unless length($_);
    if ($AGILOG) {
        if (/^agi_(\w+)\:\s+(.*)$/) {
            $AGI{$1} = $2;
        }
    }
    if (/^agi_uniqueid\:\s+(.*)$/)  { $unique_id = $1; $uniqueid = $unique_id; }
    if (/^agi_priority\:\s+(.*)$/)  { $priority  = $1; }
    if (/^agi_channel\:\s+(.*)$/)   { $channel   = $1; }
    if (/^agi_extension\:\s+(.*)$/) { $extension = $1; }
    if (/^agi_type\:\s+(.*)$/)      { $type      = $1; }
    if (/^agi_callerid\:\s+(.*)$/) { $callerid = $1; $calleridnum = $callerid; }
    if (/^agi_calleridname\:\s+(.*)$/) { $calleridname = $1; }
}
if (   ( length($callerid) > 20 )
    && ( $callerid =~ /\"\S\S\S\S\S\S\S\S\S\S\S\S\S\S\S\S\S\S/ ) )
{
    $callerid =~ s/^\"//gi;
    $callerid =~ s/\".*$//gi;
}
if (
    (
        ( length($calleridname) > 5 )
        && (   ( !$callerid )
            or ( $callerid =~ /unknown|private|00000000/i )
            or ( $callerid =~ /5551212/ ) )
    )
    or (   ( length($calleridname) > 17 )
        && ( $calleridname =~ /\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d/ ) )
    or (   ( length($calleridname) > 17 )
        && ( $calleridname =~ /\d\d\d\d\d\dW\d\d\d\d\d\d\d\d\d\dW$/ ) )
  )
{
    $callerid = $calleridname;
}
if ($AGILOG) { $agi_string = "AGI Environment Dump:"; &agi_output; }
foreach $i ( sort keys %AGI ) {
    if ($AGILOG) { $agi_string = " -- $i = $AGI{$i}"; &agi_output; }
}
if ($AGILOG) {
    $agi_string =
      "AGI Variables: |$unique_id|$channel|$extension|$type|$callerid|";
    &agi_output;
}
$VDADcampaign       = '';
$VDADphone          = '';
$VDADphone_code     = '';
$auto_dial_timeout  = '60';
$cpd_amd_action     = 'DISABLED';
$cpd_unknown_action = 'DISABLED';
$callerid =~ s/\"//gi;
$callerid =~ s/ .*//gi;
$CIDlead_id = $callerid;

if ( $CIDlead_id =~ /W\d\d\d\d\d\d\d\d\d\dW$/ ) {
    @CIDlead_id_array = split( /W/, $CIDlead_id );
    $CIDlead_id       = $CIDlead_id_array[1];
}
else {
    $CIDlead_id = substr( $CIDlead_id, 10, 10 );
}
$CIDlead_id = ( $CIDlead_id + 0 );
if ( ( $CLIlead_id > 0 ) && ( $CIDlead_id < 1 ) ) { $CIDlead_id = $CLIlead_id; }
$VD_lead_id = $CIDlead_id;
if ($AGILOG) {
    $agi_string =
"+++++ VARIABLE SET START : |$CIDlead_id|$now_date|$AST_ver|$priority|$calleridname|";
    &agi_output;
}
$stmtA =
"SELECT campaign_id,phone_number FROM vicidial_auto_calls where callerid='$callerid' order by auto_call_id desc limit 1;";
$sthA = $dbhA->prepare($stmtA) or die "preparing: ",        $dbhA->errstr;
$sthA->execute                 or die "executing: $stmtA ", $dbhA->errstr;
$sthArows = $sthA->rows;
if ($AGILOG) { $agi_string = "$sthArows|$stmtA|"; &agi_output; }
if ( $sthArows > 0 ) {
    @aryA          = $sthA->fetchrow_array;
    $campaign_id   = $aryA[0];
    $dialed_number = $aryA[1];
    $sthA->finish();
}
$stmtA =
"SELECT dial_timeout,cpd_amd_action,cpd_unknown_action FROM vicidial_campaigns where campaign_id='$campaign_id' limit 1;";
$sthA = $dbhA->prepare($stmtA) or die "preparing: ",        $dbhA->errstr;
$sthA->execute                 or die "executing: $stmtA ", $dbhA->errstr;
$sthArows = $sthA->rows;
if ($AGILOG) { $agi_string = "$sthArows|$stmtA|"; &agi_output; }
if ( $sthArows > 0 ) {
    @aryA              = $sthA->fetchrow_array;
    $auto_dial_timeout = $aryA[0];
    if ( $callerid =~ /^V/ ) {
        $cpd_amd_action     = $aryA[1];
        $cpd_unknown_action = $aryA[2];
    }
    $sthA->finish();
}
$stmtA =
"SELECT lead_id,entry_date,modify_date,status,user,vendor_lead_code,source_id,list_id,phone_number,title,first_name,middle_initial,last_name,address1,address2,address3,city,state,province,postal_code,country_code,gender,date_of_birth,alt_phone,email,security_phrase,comments,called_count,last_local_call_time,rank,owner,phone_code,called_since_last_reset,entry_list_id,gmt_offset_now FROM vicidial_list where lead_id='$VD_lead_id';";
$sthA = $dbhA->prepare($stmtA) or die "preparing: ",        $dbhA->errstr;
$sthA->execute                 or die "executing: $stmtA ", $dbhA->errstr;
$sthArows = $sthA->rows;
if ( $sthArows > 0 ) {
    @aryA                    = $sthA->fetchrow_array;
    $lead_id                 = $aryA[0];
    $entry_date              = $aryA[1];
    $modify_date             = $aryA[2];
    $status                  = $aryA[3];
    $user                    = $aryA[4];
    $vendor_lead_code        = $aryA[5];
    $source_id               = $aryA[6];
    $list_id                 = $aryA[7];
    $phone_number            = $aryA[8];
    $title                   = $aryA[9];
    $first_name              = $aryA[10];
    $middle_initial          = $aryA[11];
    $last_name               = $aryA[12];
    $address1                = $aryA[13];
    $address2                = $aryA[14];
    $address3                = $aryA[15];
    $city                    = $aryA[16];
    $state                   = $aryA[17];
    $province                = $aryA[18];
    $postal_code             = $aryA[19];
    $country_code            = $aryA[20];
    $gender                  = $aryA[21];
    $date_of_birth           = $aryA[22];
    $alt_phone               = $aryA[23];
    $email                   = $aryA[24];
    $security_phrase         = $aryA[25];
    $comments                = $aryA[26];
    $called_count            = $aryA[27];
    $last_local_call_time    = $aryA[28];
    $rank                    = $aryA[29];
    $owner                   = $aryA[30];
    $phone_code              = $aryA[31];
    $called_since_last_reset = $aryA[32];
    $entry_list_id           = $aryA[33];
    $gmt_offset_now          = $aryA[34];
}
$sthA->finish();
$lead_id                 =~ s/ /+/gi;
$entry_date              =~ s/ /+/gi;
$modify_date             =~ s/ /+/gi;
$status                  =~ s/ /+/gi;
$user                    =~ s/ /+/gi;
$vendor_lead_code        =~ s/ /+/gi;
$source_id               =~ s/ /+/gi;
$list_id                 =~ s/ /+/gi;
$phone_number            =~ s/ /+/gi;
$title                   =~ s/ /+/gi;
$first_name              =~ s/ /+/gi;
$middle_initial          =~ s/ /+/gi;
$last_name               =~ s/ /+/gi;
$address1                =~ s/ /+/gi;
$address2                =~ s/ /+/gi;
$address3                =~ s/ /+/gi;
$city                    =~ s/ /+/gi;
$state                   =~ s/ /+/gi;
$province                =~ s/ /+/gi;
$postal_code             =~ s/ /+/gi;
$country_code            =~ s/ /+/gi;
$gender                  =~ s/ /+/gi;
$date_of_birth           =~ s/ /+/gi;
$alt_phone               =~ s/ /+/gi;
$email                   =~ s/ /+/gi;
$security_phrase         =~ s/ /+/gi;
$comments                =~ s/ /+/gi;
$called_count            =~ s/ /+/gi;
$last_local_call_time    =~ s/ /+/gi;
$rank                    =~ s/ /+/gi;
$owner                   =~ s/ /+/gi;
$phone_code              =~ s/ /+/gi;
$called_since_last_reset =~ s/ /+/gi;
$entry_list_id           =~ s/ /+/gi;
$gmt_offset_now          =~ s/ /+/gi;
$campaign_id             =~ s/ /+/gi;
$dialed_number           =~ s/ /+/gi;
$AGI->exec("EXEC Set(_lead_id=$lead_id)");
$AGI->exec("EXEC Set(_entry_date=$entry_date)");
$AGI->exec("EXEC Set(_modify_date=$modify_date)");
$AGI->exec("EXEC Set(_status=$status)");
$AGI->exec("EXEC Set(_user=$user)");
$AGI->exec("EXEC Set(_vendor_lead_code=$vendor_lead_code)");
$AGI->exec("EXEC Set(_source_id=$source_id)");
$AGI->exec("EXEC Set(_list_id=$list_id)");
$AGI->exec("EXEC Set(_phone_number=$phone_number)");
$AGI->exec("EXEC Set(_title=$title)");
$AGI->exec("EXEC Set(_first_name=$first_name)");
$AGI->exec("EXEC Set(_middle_initial=$middle_initial)");
$AGI->exec("EXEC Set(_last_name=$last_name)");
$AGI->exec("EXEC Set(_address1=$address1)");
$AGI->exec("EXEC Set(_address2=$address2)");
$AGI->exec("EXEC Set(_address3=$address3)");
$AGI->exec("EXEC Set(_city=$city)");
$AGI->exec("EXEC Set(_state=$state)");
$AGI->exec("EXEC Set(_province=$province)");
$AGI->exec("EXEC Set(_postal_code=$postal_code)");
$AGI->exec("EXEC Set(_country_code=$country_code)");
$AGI->exec("EXEC Set(_gender=$gender)");
$AGI->exec("EXEC Set(_date_of_birth=$date_of_birth)");
$AGI->exec("EXEC Set(_alt_phone=$alt_phone)");
$AGI->exec("EXEC Set(_email=$email)");
$AGI->exec("EXEC Set(_security_phrase=$security_phrase)");
$AGI->exec("EXEC Set(_comments=$comments)");
$AGI->exec("EXEC Set(_called_count=$called_count)");
$AGI->exec("EXEC Set(_last_local_call_time=$last_local_call_time)");
$AGI->exec("EXEC Set(_rank=$rank)");
$AGI->exec("EXEC Set(_owner=$owner)");
$AGI->exec("EXEC Set(_phone_code=$phone_code)");
$AGI->exec("EXEC Set(_called_since_last_reset=$called_since_last_reset)");
$AGI->exec("EXEC Set(_entry_list_id=$entry_list_id)");
$AGI->exec("EXEC Set(_gmt_offset_now=$gmt_offset_now)");
$AGI->exec("EXEC Set(_campaign_id=$campaign_id)");
$AGI->exec("EXEC Set(_dialed_number=$dialed_number)");
$AGI->exec("EXEC Set(_auto_dial_timeout=$auto_dial_timeout)");
$AGI->exec("EXEC Set(_cpd_amd_action=$cpd_amd_action)");
$AGI->exec("EXEC Set(_cpd_unknown_action=$cpd_unknown_action)");
$dbhA->disconnect();

if ($AGILOG) {
    $agi_string =
"+++++ VARIABLE SET DONE EXITING : |$CIDlead_id|$now_date|$calleridname|$phone_number|";
    &agi_output;
}
exit;

sub checkresult {
    my ($res) = @_;
    my $retval;
    $tests++;
    chomp $res;
    if ( $res =~ /^200/ ) {
        $res =~ /result=(-?\d+)/;
        if ( !length($1) ) {
            $fail++;
        }
        else {
            $pass++;
        }
    }
    else {
        $fail++;
    }
}

sub agi_output {
    if ( $AGILOG >= 2 ) {
        open( Lout, ">>$AGILOGfile" )
          || die "Can't open $AGILOGfile: $!\n";
        print Lout "$now_date|$script|$agi_string\n";
        close(Lout);
    }
    if ( ( $AGILOG == '1' ) || ( $AGILOG == '3' ) ) {
        print STDERR "$now_date|$script|$agi_string\n";
    }
    $agi_string = '';
}
