#!/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             = 'cm_VID_SPECIAL.agi';
$dtmf_silent_prefix = '7';
$DROP_TIME =
  720;    ### default number of seconds to wait until you drop a waiting call
$start_moh                 = 1;
$wait_prompt_runs          = 0;
$at                        = '@';
$S                         = '*';
$mel                       = 1;        # Mysql Error Log enabled = 1
$mysql_log_count           = 272;
$one_mysql_log             = 0;
$dial_ingroup_flag         = 0;
$called_count              = 1;
$entry_list_id             = 0;
$areacode_filter_run       = 0;
$no_agent_no_queue_checked = 0;
$MT[0]                     = '';
$now_date_epoch            = time();
( $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"; }
$hm                = "$hour$min";
$hm                = ( $hm + 0 );
$epochFOURhoursAGO = ( $now_date_epoch - 14400 );
( $Ssec, $Smin, $Shour, $Smday, $Smon, $Syear, $Swday, $Syday, $Sisdst ) =
  localtime($epochFOURhoursAGO);
$Smon++;
$Syear = ( $Syear + 1900 );
if ( $Smon < 10 )  { $Smon  = "0$Smon"; }
if ( $Smday < 10 ) { $Smday = "0$Smday"; }
if ( $Shour < 10 ) { $Shour = "0$Shour"; }
if ( $Smin < 10 )  { $Smin  = "0$Smin"; }
if ( $Ssec < 10 )  { $Ssec  = "0$Ssec"; }
$timeFOURhoursAGO        = "$Syear-$Smon-$Smday $Shour:$Smin:$Ssec";
$epochTWENTYFOURhoursAGO = ( $now_date_epoch - 86400 );
( $Ssec, $Smin, $Shour, $Smday, $Smon, $Syear, $Swday, $Syday, $Sisdst ) =
  localtime($epochTWENTYFOURhoursAGO);
$Smon++;
$Syear = ( $Syear + 1900 );
if ( $Smon < 10 )  { $Smon  = "0$Smon"; }
if ( $Smday < 10 ) { $Smday = "0$Smday"; }
if ( $Shour < 10 ) { $Shour = "0$Shour"; }
if ( $Smin < 10 )  { $Smin  = "0$Smin"; }
if ( $Ssec < 10 )  { $Ssec  = "0$Ssec"; }
$timeTWENTYFOURhoursAGO = "$Syear-$Smon-$Smday $Shour:$Smin:$Ssec";
$start_epoch            = $now_date_epoch;
$now_date               = "$year-$mon-$mday $hour:$min:$sec";
$CLInow_date            = "$year-$mon-$mday\\ $hour:$min:$sec";
$YMD                    = "$year-$mon-$mday";
$start_time             = $now_date;
$CIDdate                = "$mon$mday$hour$min$sec";
$tsSQLdate              = "$year$mon$mday$hour$min$sec";
$SQLdate                = "$year-$mon-$mday $hour:$min:$sec";
$SQLdateBEGIN           = $SQLdate;
$ORIGINAL_call_time     = $SQLdate;

while ( length($CIDdate) > 9 ) {
    $CIDdate =~ s/^.//gi;
}    # 0902235959 changed to 902235959
if ( $wday == '0' ) { $now_weekday = 'SUNDAY'; }
if ( $wday == '1' ) { $now_weekday = 'MONDAY'; }
if ( $wday == '2' ) { $now_weekday = 'TUESDAY'; }
if ( $wday == '3' ) { $now_weekday = 'WEDNESDAY'; }
if ( $wday == '4' ) { $now_weekday = 'THURSDAY'; }
if ( $wday == '5' ) { $now_weekday = 'FRIDAY'; }
if ( $wday == '6' ) { $now_weekday = 'SATURDAY'; }
$BDtarget = ( $now_date_epoch - 7 );
( $Bsec, $Bmin, $Bhour, $Bmday, $Bmon, $Byear, $Bwday, $Byday, $Bisdst ) =
  localtime($BDtarget);
$Byear = ( $Byear + 1900 );
$Bmon++;
if ( $Bmon < 10 )  { $Bmon  = "0$Bmon"; }
if ( $Bmday < 10 ) { $Bmday = "0$Bmday"; }
if ( $Bhour < 10 ) { $Bhour = "0$Bhour"; }
if ( $Bmin < 10 )  { $Bmin  = "0$Bmin"; }
if ( $Bsec < 10 )  { $Bsec  = "0$Bsec"; }
$BDtsSQLdate = "$Byear$Bmon$Bmday$Bhour$Bmin$Bsec";
$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"; }
if ( !$PRSLOGfile )  { $PRSLOGfile  = "$PATHlogs/prsout.$year-$mon-$mday"; }
if ( !$PRSTESTfile ) { $PRSTESTfile = "$PATHlogs/prstest.$year-$mon-$mday"; }
if ( !$ERRLOGfile )  { $ERRLOGfile  = "$PATHlogs/MySQLerror.$year-$mon-$mday"; }
use DBI;
use Time::HiRes ( 'gettimeofday', 'usleep', 'sleep' )
  ;    # necessary to have perl sleep command of less than one second
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,local_gmt 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;
$dbhP         = $dbhA;
$mysql_count  = '02001';
$MEL_aff_rows = $sthArows;
&mysql_error_logging;
$rec_count = 0;

while ( $sthArows > $rec_count ) {
    $AGILOG       = '0';
    @aryA         = $sthA->fetchrow_array;
    $DBagi_output = $aryA[0];
    $local_gmt    = $aryA[1];
    if ($isdst)                      { $local_gmt++; }
    if ( $DBagi_output =~ /STDERR/ ) { $AGILOG = '1'; }
    if ( $DBagi_output =~ /FILE/ )   { $AGILOG = '2'; }
    if ( $DBagi_output =~ /BOTH/ )   { $AGILOG = '3'; }
    $rec_count++;
}
$sthA->finish();
$stmtA =
"SELECT enable_queuemetrics_logging,queuemetrics_server_ip,queuemetrics_dbname,queuemetrics_login,queuemetrics_pass,queuemetrics_log_id,queuemetrics_eq_prepend,queuemetrics_pe_phone_append,did_agent_log,alt_log_server_ip,alt_log_dbname,alt_log_login,alt_log_pass,tables_use_alt_log_db,did_ra_extensions_enabled,queuemetrics_socket,queuemetrics_socket_url,enable_did_entry_list_id,enable_drop_lists,inbound_answer_config,agent_search_method,abandon_check_queue,inbound_credits FROM system_settings;";
$sthA = $dbhA->prepare($stmtA) or die "preparing: ",        $dbhA->errstr;
$sthA->execute                 or die "executing: $stmtA ", $dbhA->errstr;
$sthArows     = $sthA->rows;
$dbhP         = $dbhA;
$mysql_count  = '02026';
$MEL_aff_rows = $sthArows;
&mysql_error_logging;

if ( $sthArows > 0 ) {
    @aryA                         = $sthA->fetchrow_array;
    $enable_queuemetrics_logging  = $aryA[0];
    $queuemetrics_server_ip       = $aryA[1];
    $queuemetrics_dbname          = $aryA[2];
    $queuemetrics_login           = $aryA[3];
    $queuemetrics_pass            = $aryA[4];
    $queuemetrics_log_id          = $aryA[5];
    $queuemetrics_eq_prepend      = $aryA[6];
    $queuemetrics_pe_phone_append = $aryA[7];
    $did_agent_log                = $aryA[8];
    $alt_log_server_ip            = $aryA[9];
    $alt_log_dbname               = $aryA[10];
    $alt_log_login                = $aryA[11];
    $alt_log_pass                 = $aryA[12];
    $tables_use_alt_log_db        = $aryA[13];
    $did_ra_extensions_enabled    = $aryA[14];
    $queuemetrics_socket          = $aryA[15];
    $queuemetrics_socket_url      = $aryA[16];
    $enable_did_entry_list_id     = $aryA[17];
    $enable_drop_lists            = $aryA[18];
    $inbound_answer_config        = $aryA[19];
    $SSagent_search_method        = $aryA[20];
    $SSabandon_check_queue        = $aryA[21];
    $SSinbound_credits            = $aryA[22];
}
$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] );
    $call_handle_method     = $ARGV_vars[0];
    $search_method          = $ARGV_vars[1];
    $list_id                = $ARGV_vars[2];
    $phone_code             = $ARGV_vars[3];
    $Scampaign_id           = $ARGV_vars[4];
    $vid_enter_filename     = $ARGV_vars[5];
    $vid_id_number_filename = $ARGV_vars[6];
    $vid_confirm_filename   = $ARGV_vars[7];
    $vid_validate_digits    = $ARGV_vars[8];
    $vid_special_container  = $ARGV_vars[9];
}
$| = 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_channel\:\s+(.*)$/)   { $channel   = $1; }
    if (/^agi_extension\:\s+(.*)$/) { $extension = $1; }
    if (/^agi_type\:\s+(.*)$/)      { $type      = $1; }
    if (/^agi_callerid\:\s+(.*)$/)  { $callerid  = $1; }
    if (/^agi_calleridname\:\s+(.*)$/) { $calleridname = $1; }
    if (/^agi_context\:\s+(.*)$/)      { $context      = $1; }
}
$callerid     =~ s/\'|\\\\|\\\|\\|\\;|\\\;|\;|;//gi;
$calleridname =~ s/\'|\\\\|\\\|\\|\\;|\\\;|\;|;//gi;
$extension    =~ s/\'|\"|\\\\|\\\|\\|\\;|\\\;|\;|;//gi;
if ( $calleridname =~
/^V\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d|^Y\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d/
  )
{
    $callerid = $calleridname;
}
if (   ( $callerid =~ /\".*\"/ )
    && ( ( !$calleridname ) or ( $calleridname =~ /unknown/ ) ) )
{
    $calleridname = $callerid;
    $calleridname =~ s/\<\d\d\d\d\d\d\d\d\d\d\>//gi;
    $calleridname =~ s/\"|\" //gi;
}
if ( $callerid !~
/^V\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d|^Y\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d/
  )
{
    $callerid     =~ s/\D|\'//gi;
    $calleridname =~ s/unknown|\'//gi;
    if ( ( !$callerid ) or ( $callerid =~ /unknown/ ) ) {
        $callerid = $calleridname;
    }
}
$prev_callerid = $callerid;
if ( $calleridname =~ /^J\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d/ ) {
    $prev_callerid = $calleridname;
}
if (   ( $phone_code =~ /^1$/ )
    && ( $callerid =~ /^1/ )
    && ( length($callerid) > 10 ) )
{
    $callerid =~ s/^1//gi;
    if ($AGILOG) {
        $agi_string = "North America CID Check: $phone_code|$callerid|";
        &agi_output;
    }
}
$originalCID = $callerid;
if ( ( $call_handle_method =~ /^CID/ ) || ( $call_handle_method =~ /^VID/ ) ) {
    if   ( length($callerid) > 0 ) { $phone_number = $callerid; }
    else                           { $phone_number = ''; }
    if   ( length($calleridname) > 0 ) { $VLcomments = $calleridname; }
    else                               { $VLcomments = ''; }
}
if ( length($callerid) < 10 ) { $callerid = $parked_by; }
if ( length($pin) > 0 )       { $callerid = $pin; }
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;
}
if ( length($pin) < 1 ) { $pin = $inbound_number; }
$fronter = $pin;
if ($AGILOG) {
    $agi_string =
"+++++ VID PROMPT SPECIAL STARTED : |$channel_group|$callerid-$pin|$now_date";
    &agi_output;
}
$VDADphone      = '';
$VDADphone_code = '';
$VCcallerid     = $channel_group;
$VD_campaign_id = $channel_group;
if ( length($VCcallerid) < 2 ) { $VCcallerid = 'ViciDial Inbound'; }
$cbc = 0;
$stmtA =
"SELECT voicemail_dump_exten,ext_context,answer_transfer_agent,local_gmt,asterisk_version,max_vicidial_trunks,voicemail_dump_exten_no_inst,routing_prefix 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;
$dbhP         = $dbhA;
$mysql_count  = '02004';
$MEL_aff_rows = $sthArows;
&mysql_error_logging;

while ( $sthArows > $cbc ) {
    @aryA                         = $sthA->fetchrow_array;
    $DBvoicemail_dump_exten       = $aryA[0];
    $DBext_context                = $aryA[1];
    $DBanswer_transfer_agent      = $aryA[2];
    $DBSERVER_GMT                 = $aryA[3];
    $asterisk_version             = $aryA[4];
    $DBmax_vicidial_trunks        = $aryA[5];
    $voicemail_dump_exten_no_inst = $aryA[6];
    $routing_prefix               = $aryA[7];

    if ($DBvoicemail_dump_exten) {
        $voicemail_dump_exten = $DBvoicemail_dump_exten;
    }
    if ($DBext_context) { $ext_context = $DBext_context; }
    if ($DBanswer_transfer_agent) {
        $answer_transfer_agent = $DBanswer_transfer_agent;
    }
    if ($DBSERVER_GMT)     { $SERVER_GMT = $DBSERVER_GMT; }
    if ($asterisk_version) { $AST_ver    = $asterisk_version; }
    if ($DBmax_vicidial_trunks) {
        $max_vicidial_trunks = $DBmax_vicidial_trunks;
    }
    $LOCAL_GMT_OFF     = $SERVER_GMT;
    $LOCAL_GMT_OFF_STD = $SERVER_GMT;
    if ($isdst) { $LOCAL_GMT_OFF++; }
    if ($DB) {
        print
"SEED TIME  $now_date_epoch      :   $year-$mon-$mday $hour:$min:$sec  LOCAL GMT OFFSET NOW: $LOCAL_GMT_OFF\n";
    }
    $cbc++;
}
$sthA->finish();
$not_found_action = 's';
$new_lead_ingroup = '';
$default_ingroup  = '';
$match_ingroup    = '';
$container_lines  = 0;
@container_array  = @MT;

if ( length($vid_special_container) > 0 ) {
    $stmtA =
"SELECT container_entry FROM vicidial_settings_containers where container_id='$vid_special_container' and container_type='CM_VIDPROMPT_SPECIAL';";
    if ($DBX) { print "   |$stmtA|\n"; }
    $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;
        $VIDScontainer_entry = $aryA[0];
        $VIDScontainer_entry =~ s/\r|\t|\'|\"//gi;
        @VIDScontainer_array = split( /\n/, $VIDScontainer_entry );
        $VIDSc               = 0;
        foreach (@VIDScontainer_array) {
            if (   ( $VIDScontainer_array[$VIDSc] !~ /^;/ )
                && ( length( $VIDScontainer_array[$VIDSc] ) > 0 ) )
            {
                $container_array[$container_lines] =
                  "$VIDScontainer_array[$VIDSc]";
                $container_lines++;
                if ( $VIDScontainer_array[$VIDSc] =~
                    /not_found_action => |not_found_action=>/ )
                {
                    $not_found_action = $VIDScontainer_array[$VIDSc];
                    $not_found_action =~
                      s/not_found_action => |not_found_action=>//gi;
                    $not_found_action =~ s/[^-_0-9a-zA-Z]//gi;
                    if ( length($not_found_action) < 1 ) {
                        $not_found_action = 'S';
                    }
                }
                if ( $VIDScontainer_array[$VIDSc] =~
                    /new_lead_ingroup => |new_lead_ingroup=>/ )
                {
                    $new_lead_ingroup = $VIDScontainer_array[$VIDSc];
                    $new_lead_ingroup =~
                      s/new_lead_ingroup => |new_lead_ingroup=>//gi;
                    $new_lead_ingroup =~ s/[^-_0-9a-zA-Z]//gi;
                }
                if ( $VIDScontainer_array[$VIDSc] =~
                    /default_ingroup => |default_ingroup=>/ )
                {
                    $default_ingroup = $VIDScontainer_array[$VIDSc];
                    $default_ingroup =~
                      s/default_ingroup => |default_ingroup=>//gi;
                    $default_ingroup =~ s/[^-_0-9a-zA-Z]//gi;
                }
            }
            $VIDSc++;
        }
    }
    $sthA->finish();
}
if ( $container_lines < 2 ) {
    if ($AGILOG) {
        $agi_string =
"VID-SPECIAL container invalid!  transferring to 's'  |$vid_special_container|$channel|$callerid|";
        &agi_output;
    }
    print "SET CONTEXT $context\n";
    $result = <STDIN>;
    checkresult($result);
    print "SET EXTENSION s\n";
    $result = <STDIN>;
    checkresult($result);
    print "SET PRIORITY 1\n";
    $result = <STDIN>;
    checkresult($result);
}
if ( ( length($new_lead_ingroup) < 1 ) && ( length($default_ingroup) > 0 ) ) {
    $new_lead_ingroup = $default_ingroup;
}
$LOGuser = 'VDCL';
$AGI->stream_file('sip-silence');
$AGI->stream_file('sip-silence');
if ( $call_handle_method =~ /^VIDPROMPT/ ) {
    $vendor_lead_code = $AGI->get_variable('vendor_lead_code');
    if ( ($AGILOG) && ( length($vendor_lead_code) > 0 ) ) {
        $agi_string = "vendor id AGI variable:    |$vendor_lead_code|";
        &agi_output;
    }
    if ( length($vendor_lead_code) > 2 ) {
        $vendor_id = $vendor_lead_code;
    }
    else {
        &enter_id_number;
    }
}
if ( $call_handle_method =~ /LOOKUP/ ) {
    $listSQL = '';
    if ( $call_handle_method =~ /LOOKUPRL/ ) {
        $listSQL = "and list_id='$list_id'";
    }
    else {
        if ( $call_handle_method =~ /LOOKUPRC/ ) {
            $cbc       = 0;
            $SlistsSQL = '';
            $stmtA =
"SELECT list_id FROM vicidial_lists where campaign_id='$Scampaign_id' limit 1000;";
            $sthA = $dbhA->prepare($stmtA) or die "preparing: ", $dbhA->errstr;
            $sthA->execute or die "executing: $stmtA ",          $dbhA->errstr;
            $sthArows     = $sthA->rows;
            $dbhP         = $dbhA;
            $mysql_count  = '02009';
            $MEL_aff_rows = $sthArows;
            &mysql_error_logging;

            while ( $sthArows > $cbc ) {
                @aryA = $sthA->fetchrow_array;
                $SlistsSQL .= "'$aryA[0]',";
                $cbc++;
            }
            $sthA->finish();
            chop($SlistsSQL);
            if ( length($SlistsSQL) > 3 ) {
                $listSQL = "and list_id IN($SlistsSQL)";
            }
        }
    }
    $stmtA =
"SELECT lead_id,called_count,list_id,phone_number from vicidial_list where vendor_lead_code='$vendor_id' $listSQL order by last_local_call_time desc limit 1;";
    if ($AGILOG) {
        $agi_string = "VDAD vicidial_list search |$vendor_id|$stmtA|";
        &agi_output;
    }
    $sthA = $dbhA->prepare($stmtA) or die "preparing: ",        $dbhA->errstr;
    $sthA->execute                 or die "executing: $stmtA ", $dbhA->errstr;
    $sthArows     = $sthA->rows;
    $dbhP         = $dbhA;
    $mysql_count  = '02010';
    $MEL_aff_rows = $sthArows;
    &mysql_error_logging;

    if ( $sthArows > 0 ) {
        @aryA           = $sthA->fetchrow_array;
        $insert_lead_id = $aryA[0];
        $called_count   = $aryA[1];
        $list_id        = $aryA[2];
        $phone_number   = $aryA[3];
        $sthA->finish();
        if ($AGILOG) {
            $agi_string =
"VID-SPECIAL vicidial_list found |$insert_lead_id|$called_count|$list_id|$vendor_id|$stmtA|";
            &agi_output;
        }
        $i = 0;
        while ( $i < $container_lines ) {
            if ( $container_array[$i] =~ /^list_ingroup/i ) {
                $temp_line = $container_array[$i];
                $temp_line =~ s/list_ingroup => |list_ingroup=>| //gi;
                @temp_array = split( /,/, $temp_line );
                if ( $temp_array[0] =~ /^$list_id$/ ) {
                    $match_ingroup = $temp_array[1];
                    if ($AGILOG) {
                        $agi_string =
"VID-SPECIAL list in-group match found |$match_ingroup|$insert_lead_id|$list_id|$vendor_id|$stmtA|";
                        &agi_output;
                    }
                }
            }
            $i++;
        }
        if ( length($match_ingroup) < 1 ) {
            if ( length($default_ingroup) > 0 ) {
                $match_ingroup = $default_ingroup;
                if ($AGILOG) {
                    $agi_string =
"VID-SPECIAL list in-group match not found, using default |$match_ingroup|$insert_lead_id|$list_id|$vendor_id|$stmtA|";
                    &agi_output;
                }
            }
            else {
                if ($AGILOG) {
                    $agi_string =
"VID-SPECIAL no list match found and no default ingroup defined, going to 's'  |$list_id|$channel|$callerid|$vendor_id|";
                    &agi_output;
                }
                print "SET CONTEXT $context\n";
                $result = <STDIN>;
                checkresult($result);
                print "SET EXTENSION s\n";
                $result = <STDIN>;
                checkresult($result);
                print "SET PRIORITY 1\n";
                $result = <STDIN>;
                checkresult($result);
                exit;
            }
        }
        $PADlead_id = sprintf( "%010s", $insert_lead_id );
        while ( length($PADlead_id) > 10 ) { chop($PADlead_id); }
        $VIDqueryCID = "Y$CIDdate$PADlead_id";
        $newcallerid = "\"$VIDqueryCID <$phone_number>\"";
        $AGI->set_callerid($newcallerid);
        print STDERR "Setting CID \"$newcallerid\"\n";
        checkresult($result);

        if ($AGILOG) {
            $agi_string =
"VID-SPECIAL callerID changed: \"$VIDqueryCID\" \<$phone_number\>";
            &agi_output;
        }
        $AGI->exec("EXEC Set(_ingroupvar=$match_ingroup)");
        $AGI->exec("EXEC Set(_igsearchmethod=$search_method)");
        $AGI->exec("EXEC Set(_iglistid=$list_id)");
        $AGI->exec("EXEC Set(_igphonecode=$phone_code)");
        $AGI->exec("EXEC Set(_igcampaignid=$Scampaign_id)");
        $ingroup_exten_string = "A1B1C123";
        if ($AGILOG) {
            $agi_string =
"VID-SPECIAL sending to in-group  |$ingroup_exten_string|$channel|$callerid|$vendor_id|";
            &agi_output;
        }
        print "SET CONTEXT $context\n";
        $result = <STDIN>;
        checkresult($result);
        print "SET EXTENSION $ingroup_exten_string\n";
        $result = <STDIN>;
        checkresult($result);
        print "SET PRIORITY 1\n";
        $result = <STDIN>;
        checkresult($result);
        exit;
    }
    else {
        if (   ( $not_found_action =~ /new_lead/ )
            && ( length($new_lead_ingroup) > 0 ) )
        {
            $AGI->exec("EXEC Set(_ingroupvar=$new_lead_ingroup)");
            $AGI->exec("EXEC Set(_igsearchmethod=$search_method)");
            $AGI->exec("EXEC Set(_iglistid=$list_id)");
            $AGI->exec("EXEC Set(_igphonecode=$phone_code)");
            $AGI->exec("EXEC Set(_igcampaignid=$Scampaign_id)");
            $AGI->exec("EXEC Set(_igvendorid=$vendor_id)");
            $ingroup_exten_string = "A2B2C234";
            if ($AGILOG) {
                $agi_string =
"VID-SPECIAL sending new lead to in-group  |$ingroup_exten_string|$channel|$callerid|$vendor_id|";
                &agi_output;
            }
            print "SET CONTEXT $context\n";
            $result = <STDIN>;
            checkresult($result);
            print "SET EXTENSION $ingroup_exten_string\n";
            $result = <STDIN>;
            checkresult($result);
            print "SET PRIORITY 1\n";
            $result = <STDIN>;
            checkresult($result);
            exit;
        }
        else {
            if ($AGILOG) {
                $agi_string =
"VID-SPECIAL lead not found going to '$not_found_action'  |$vid_special_container|$channel|$callerid|$vendor_id|";
                &agi_output;
            }
            print "SET CONTEXT $context\n";
            $result = <STDIN>;
            checkresult($result);
            print "SET EXTENSION $not_found_action\n";
            $result = <STDIN>;
            checkresult($result);
            print "SET PRIORITY 1\n";
            $result = <STDIN>;
            checkresult($result);
            exit;
        }
    }
}
$dbhA->disconnect();
exit;

sub enter_id_number {
    $vid_validate_length = 1;
    $vendor_id           = '';
    if ( length($vid_enter_filename) < 1 ) {
        $vid_enter_filename = 'please_enter_id_number';
    }
    if ( length($vid_id_number_filename) < 1 ) {
        $vid_id_number_filename = 'id_number';
    }
    if ( length($vid_confirm_filename) < 1 ) {
        $vid_confirm_filename = 'confirm_id_number';
    }
    if ( length($vid_validate_digits) < 1 ) {
        $vid_validate_digits = 'X';
        $vid_validate_length = 0;
    }
    if ( $vid_validate_digits =~ /X/ ) {
        $vid_validate_digits = 99;
        $vid_validate_length = 0;
    }
    if ($AGILOG) {
        $agi_string =
"$call_handle_method method: |$vid_enter_filename|$vid_id_number_filename|$vid_confirm_filename|$vid_validate_digits|$vid_validate_length|";
        &agi_output;
    }
    $confirmation         = 0;
    $confirmation_chances = 0;
    while ( ( $confirmation_chances < 3 ) && ( $confirmation < 1 ) ) {
        $entry_chances = 0;
        $Lvendor_id    = 0;
        if ($AGILOG) {
            $agi_string =
"DEBUG------------------( ($entry_chances < 3) && ( ( ($Lvendor_id < 1) && ($vid_validate_length < 1) ) || ( ($Lvendor_id != $vid_validate_digits) && ($vid_validate_length > 0) ) ) )";
            &agi_output;
        }
        while (
            ( $entry_chances < 3 )
            && (
                ( ( $Lvendor_id < 1 ) && ( $vid_validate_length < 1 ) )
                || (   ( $Lvendor_id != $vid_validate_digits )
                    && ( $vid_validate_length > 0 ) )
            )
          )
        {
            $entry_chances++;
            $digits_being_entered = 1;
            $id_number            = '';
            $interrupt_digit      = '';
            $interrupt_digit =
              $AGI->stream_file( "$vid_enter_filename", '0123456789' );
            if ($AGILOG) {
                $agi_string = "interrupt_digit |$interrupt_digit|";
                &agi_output;
            }
            if ( $interrupt_digit > 0 ) {
                if ( $interrupt_digit == 48 ) { $interrupt_digit = 0; }
                if ( $interrupt_digit == 49 ) { $interrupt_digit = 1; }
                if ( $interrupt_digit == 50 ) { $interrupt_digit = 2; }
                if ( $interrupt_digit == 51 ) { $interrupt_digit = 3; }
                if ( $interrupt_digit == 52 ) { $interrupt_digit = 4; }
                if ( $interrupt_digit == 53 ) { $interrupt_digit = 5; }
                if ( $interrupt_digit == 54 ) { $interrupt_digit = 6; }
                if ( $interrupt_digit == 55 ) { $interrupt_digit = 7; }
                if ( $interrupt_digit == 56 ) { $interrupt_digit = 8; }
                if ( $interrupt_digit == 57 ) { $interrupt_digit = 9; }
                $id_number = $interrupt_digit;
            }
            $digit_loop_counter = 0;
            while ( $digits_being_entered > 0 ) {
                $digit = chr( $AGI->wait_for_digit('5000') )
                  ; # wait 5 seconds for input or until the pound key is pressed
                if ( $digit =~ /\d/ ) {
                    $id_number = "$id_number$digit";
                    if ($AGILOG) {
                        $agi_string =
                          "digit |$digit|     id_number |$id_number|";
                        &agi_output;
                    }
                    undef $digit;
                }
                else {
                    $digits_being_entered = 0;
                }
                $Lid_number = length($id_number);
                if ( $Lid_number >= $vid_validate_digits ) {
                    $digits_being_entered = 0;
                }
                $digit_loop_counter++;
            }
            $id_number =~ s/\D//gi;
            $vendor_id  = $id_number;
            $Lvendor_id = length($vendor_id);
        }
        $AGI->stream_file("$vid_id_number_filename");
        $AGI->say_digits("$vendor_id");
        if ( length($vendor_id) > 0 ) {
            $interrupt_digit =
              $AGI->stream_file( "$vid_confirm_filename", '12' );
            if ($AGILOG) {
                $agi_string = "interrupt_digit |$interrupt_digit|";
                &agi_output;
            }
            $digits_being_entered = 1;
            $ANSWER_confirm       = '';
            if ( $interrupt_digit > 0 ) {
                if ( $interrupt_digit == 49 ) { $interrupt_digit = 1; }
                if ( $interrupt_digit == 50 ) { $interrupt_digit = 2; }
                $ANSWER_confirm = $interrupt_digit;
            }
            if ( length($ANSWER_confirm) < 1 ) {
                $digit_loop_counter = 0;
                while (( $digits_being_entered > 0 )
                    && ( $digit_loop_counter < 1 ) )
                {
                    $digit = chr( $AGI->wait_for_digit('5000') )
                      ;    # wait 5 seconds for input
                    if ( $digit =~ /\d/ ) {
                        $ANSWER_confirm = "$ANSWER_confirm$digit";
                        if ($AGILOG) {
                            $agi_string =
"digit |$digit|     ANSWER_confirm |$ANSWER_confirm|";
                            &agi_output;
                        }
                        undef $digit;
                    }
                    else {
                        $digits_being_entered = 0;
                    }
                    $digit_loop_counter++;
                }
            }
            $ANSWER_confirm =~ s/\D//gi;
            if ( $ANSWER_confirm > 1 ) { $vendor_id = ''; }
            if ( ( $ANSWER_confirm > 0 ) && ( $ANSWER_confirm < 2 ) ) {
                $confirmation = 1;
            }
        }
        if ( $confirmation < 1 ) {
            $AGI->stream_file('buzz');
        }
        $confirmation_chances++;
    }
}

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

sub leading_zero($) {
    $_ = $_[0];
    s/^(\d)$/0$1/;
    s/^(\d\d)$/0$1/;
    return $_;
}    # End of the leading_zero() routine.

sub agi_output {
    ( $Lsec, $Lmin, $Lhour, $Lmday, $Lmon, $Lyear, $Lwday, $Lyday, $Lisdst ) =
      localtime(time);
    if ( $Lhour < 10 ) { $Lhour = "0$Lhour"; }
    if ( $Lmin < 10 )  { $Lmin  = "0$Lmin"; }
    if ( $Lsec < 10 )  { $Lsec  = "0$Lsec"; }
    $LOGtime = "$Lhour:$Lmin:$Lsec";
    if ( $AGILOG >= 2 ) {
        open( Lout, ">>$AGILOGfile" )
          || die "Can't open $AGILOGfile: $!\n";
        print Lout "$now_date|$LOGtime|$script|$agi_string\n";
        close(Lout);
    }
    if ( ( $AGILOG == '1' ) || ( $AGILOG == '3' ) ) {
        print STDERR "$now_date|$LOGtime|$script|$agi_string\n";
    }
    $agi_string = '';
}

sub mysql_error_logging {
    ( $Lsec, $Lmin, $Lhour, $Lmday, $Lmon, $Lyear, $Lwday, $Lyday, $Lisdst ) =
      localtime(time);
    if ( $Lhour < 10 ) { $Lhour = "0$Lhour"; }
    if ( $Lmin < 10 )  { $Lmin  = "0$Lmin"; }
    if ( $Lsec < 10 )  { $Lsec  = "0$Lsec"; }
    $LOGtime = "$Lhour:$Lmin:$Lsec";
    $errno   = '';
    $error   = '';
    if ( ( $mel > 0 ) || ( $one_mysql_log > 0 ) ) {
        $errno = $dbhP->err();
        if ( ( $errno > 0 ) || ( $mel > 1 ) || ( $one_mysql_log > 0 ) ) {
            $error = $dbhP->errstr();
            open( Eout, ">>$ERRLOGfile" )
              || die "Can't open $ERRLOGfile: $!\n";
            print Eout
"$now_date|$LOGtime|$script|$mysql_count|$MEL_aff_rows|$errno|$error|$stmtA|$callerid|$insert_lead_id|\n";
            close(Eout);
        }
    }
    $one_mysql_log = 0;
}

sub parse_asterisk_version {
    my $ast_ver_str     = $_[0];
    my @hyphen_parts    = split( /-/, $ast_ver_str );
    my $ast_ver_postfix = $hyphen_parts[1];
    my @dot_parts       = split( /\./, $hyphen_parts[0] );
    my %ast_ver_hash;
    if ( $dot_parts[0] <= 1 ) {
        %ast_ver_hash = (
            "major"    => $dot_parts[0],
            "minor"    => $dot_parts[1],
            "build"    => $dot_parts[2],
            "revision" => $dot_parts[3],
            "postfix"  => $ast_ver_postfix
        );
    }
    if ( $dot_parts[0] > 1 ) {
        %ast_ver_hash = (
            "major"    => 1,
            "minor"    => $dot_parts[0],
            "build"    => $dot_parts[1],
            "revision" => $dot_parts[2],
            "postfix"  => $ast_ver_postfix
        );
    }
    return (%ast_ver_hash);
}
