#!/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_lookup.agi';
$S      = '*';
$US     = '_';
$vicidial_list_fields =
'|lead_id|vendor_lead_code|source_id|list_id|gmt_offset_now|called_since_last_reset|phone_code|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|status|entry_date|entry_list_id|modify_date|user|q01|q02|q03|q04|q05|q06|q07|q08|q09|q10|q11|q12|q13|q14|q15|q16|q17|q18|q19|q20|q21|q22|q23|q24|q25|q26|q27|q28|q29|q30|q31|q32|q33|q34|q35|q36|q37|q38|q39|q40|q41|q42|q43|q44|q45|q46|q47|q48|q49|q50|q51|q52|q53|q54|q55|q56|q57|q58|q59|q60|q61|q62|q63|q64|q65|q66|q67|q68|q69|q70|q71|q72|q73|q74|q75|q76|q77|q78|q79|q80|q81|q82|q83|q84|q85|q86|q87|q88|q89|q90|q91|q92|q93|q94|q95|q96|q97|q98|q99|';
( $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";
$CLInow_date    = "$year-$mon-$mday\\ $hour:$min:$sec";
$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;

while ( length($CIDdate) > 9 ) {
    $CIDdate =~ s/^.//gi;
}    # 0902235959 changed to 902235959
$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 ( !$CEPLOGfile ) { $CEPLOGfile = "$PATHlogs/Cepstral.$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;

if ( $sthArows > 0 ) {
    $AGILOG       = '0';
    @aryA         = $sthA->fetchrow_array;
    $DBagi_output = $aryA[0];
    $local_gmt    = $aryA[1];
    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] );
    $field             = $ARGV_vars[0];
    $search_method     = $ARGV_vars[1];
    $search_id         = $ARGV_vars[2];
    $tts_prompt        = $ARGV_vars[3];
    $phone_update      = $ARGV_vars[4];
    $uniqueid_address3 = $ARGV_vars[5];
    $agent_id_update   = $ARGV_vars[6];
    $title_update      = $ARGV_vars[7];
}
if ( ( length($field) < 2 ) || ( $vicidial_list_fields !~ /\|$field\|/ ) ) {
    $field = 'vendor_lead_code';
}
if ( length($search_method) < 1 ) { $search_method = 'SYSTEM'; }
if ( length($search_id) < 1 )     { $search_method = 'SYSTEM'; }
$| = 1;
while (<STDIN>) {
    chomp;
    last unless length($_);
    if ($AGILOG) {
        if (/^agi_(\w+)\:\s+(.*)$/) {
            $AGI{$1} = $2;
        }
    }
    if (/^agi_context\:\s+(.*)$/)   { $context   = $1; }
    if (/^agi_priority\:\s+(.*)$/)  { $priority  = $1; }
    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 (   ( $callerid =~ /\".*\"/ )
    && ( ( !$calleridname ) or ( $calleridname =~ /unknown/ ) ) )
{
    $calleridname = $callerid;
    $calleridname =~ s/\<\d\d\d\d\d\d\d\d\d\d\>//gi;
    $calleridname =~ s/\"|\" //gi;
}
$callerid     =~ s/\D|\'//gi;
$calleridname =~ s/unknown|\'//gi;
if ( ( !$callerid ) or ( $callerid =~ /unknown/ ) ) {
    $callerid = $calleridname;
}
$extension =~ s/\D//gi;
$agent_user_id  = $AGI->get_variable('agent_user_id');
$call_var_title = $AGI->get_variable('title');
if ( ($AGILOG) && ( length($agent_user_id) > 0 ) ) {
    $agi_string = "user id AGI variables:    |$agent_user_id|$call_var_title|";
    &agi_output;
}
$listSQL = '';
if ( $search_method =~ /LIST$/ ) { $listSQL = "and list_id='$search_id'"; }
if ( $search_method =~ /CAMPAIGNLISTS$|CAMPLISTSALL$/ ) {
    $activeSQL = '';
    if ( $search_method =~ /CAMPAIGNLISTS$/ ) {
        $activeSQL = "where active='Y'";
    }
    $cbc       = 0;
    $SlistsSQL = '';
    $stmtA =
"SELECT list_id FROM vicidial_lists where campaign_id='$search_id' $activeSQL limit 1000;";
    $sthA = $dbhA->prepare($stmtA) or die "preparing: ",        $dbhA->errstr;
    $sthA->execute                 or die "executing: $stmtA ", $dbhA->errstr;
    $sthArows = $sthA->rows;
    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)"; }
}
if ($AGILOG) {
    $agi_string =
      "searching for account by $field|$search_method|$search_id|$extension";
    &agi_output;
}
$found_extension = 'B';
$found_priority  = '1';
$stmtA =
"SELECT lead_id,phone_number,first_name,last_name from vicidial_list where $field='$extension' $listSQL order by last_local_call_time desc limit 1;";
$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];
    $phone_number = $aryA[1];
    $first_name   = $aryA[2];
    $last_name    = $aryA[3];
    $sthA->finish();
    $found_extension = 'A';
    $found_priority  = '1';
    $confirmation    = 1;

    if ( length($tts_prompt) > 1 ) {
        if ($AGILOG) { $agi_string = "--    TTS : |$tts_prompt|"; &agi_output; }
        $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 FROM vicidial_list where lead_id='$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;
            $TTS_lead_id              = $aryA[0];
            $TTS_entry_date           = $aryA[1];
            $TTS_modify_date          = $aryA[2];
            $TTS_status               = $aryA[3];
            $TTS_user                 = $aryA[4];
            $TTS_vendor_lead_code     = $aryA[5];
            $TTS_source_id            = $aryA[6];
            $TTS_list_id              = $aryA[7];
            $TTS_phone_number         = $aryA[8];
            $TTS_title                = $aryA[9];
            $TTS_first_name           = $aryA[10];
            $TTS_middle_initial       = $aryA[11];
            $TTS_last_name            = $aryA[12];
            $TTS_address1             = $aryA[13];
            $TTS_address2             = $aryA[14];
            $TTS_address3             = $aryA[15];
            $TTS_city                 = $aryA[16];
            $TTS_state                = $aryA[17];
            $TTS_province             = $aryA[18];
            $TTS_postal_code          = $aryA[19];
            $TTS_country_code         = $aryA[20];
            $TTS_gender               = $aryA[21];
            $TTS_date_of_birth        = $aryA[22];
            $TTS_alt_phone            = $aryA[23];
            $TTS_email                = $aryA[24];
            $TTS_security_phrase      = $aryA[25];
            $TTS_comments             = $aryA[26];
            $TTS_called_count         = $aryA[27];
            $TTS_last_local_call_time = $aryA[28];
            $TTS_rank                 = $aryA[29];
            $TTS_owner                = $aryA[30];
        }
        $sthA->finish();
        $stmtA =
"SELECT tts_text,tts_voice FROM vicidial_tts_prompts where tts_id='$tts_prompt';";
        $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;
            $TTS_voice = $aryA[1];
            $TTS_text  = $aryA[0];
            $TTS_text =~ s/--A--lead_id--B--/$TTS_lead_id/gi;
            $TTS_text =~ s/--A--entry_date--B--/$TTS_entry_date/gi;
            $TTS_text =~ s/--A--modify_date--B--/$TTS_modify_date/gi;
            $TTS_text =~ s/--A--status--B--/$TTS_status/gi;
            $TTS_text =~ s/--A--user--B--/$TTS_user/gi;
            $TTS_text =~ s/--A--vendor_lead_code--B--/$TTS_vendor_lead_code/gi;
            $TTS_text =~ s/--A--source_id--B--/$TTS_source_id/gi;
            $TTS_text =~ s/--A--list_id--B--/$TTS_list_id/gi;
            $TTS_text =~ s/--A--phone_number--B--/$TTS_phone_number/gi;
            $TTS_text =~ s/--A--title--B--/$TTS_title/gi;
            $TTS_text =~ s/--A--first_name--B--/$TTS_first_name/gi;
            $TTS_text =~ s/--A--middle_initial--B--/$TTS_middle_initial/gi;
            $TTS_text =~ s/--A--last_name--B--/$TTS_last_name/gi;
            $TTS_text =~ s/--A--address1--B--/$TTS_address1/gi;
            $TTS_text =~ s/--A--address2--B--/$TTS_address2/gi;
            $TTS_text =~ s/--A--address3--B--/$TTS_address3/gi;
            $TTS_text =~ s/--A--city--B--/$TTS_city/gi;
            $TTS_text =~ s/--A--state--B--/$TTS_state/gi;
            $TTS_text =~ s/--A--province--B--/$TTS_province/gi;
            $TTS_text =~ s/--A--postal_code--B--/$TTS_postal_code/gi;
            $TTS_text =~ s/--A--country_code--B--/$TTS_country_code/gi;
            $TTS_text =~ s/--A--gender--B--/$TTS_gender/gi;
            $TTS_text =~ s/--A--date_of_birth--B--/$TTS_date_of_birth/gi;
            $TTS_text =~ s/--A--alt_phone--B--/$TTS_alt_phone/gi;
            $TTS_text =~ s/--A--email--B--/$TTS_email/gi;
            $TTS_text =~ s/--A--security_phrase--B--/$TTS_security_phrase/gi;
            $TTS_text =~ s/--A--comments--B--/$TTS_comments/gi;
            $TTS_text =~ s/--A--called_count--B--/$TTS_called_count/gi;
            $TTS_text =~
              s/--A--last_local_call_time--B--/$TTS_last_local_call_time/gi;
            $TTS_text =~ s/--A--rank--B--/$TTS_rank/gi;
            $TTS_text =~ s/--A--owner--B--/$TTS_owner/gi;

            if ( ( $TTS_text =~ /--C--/ ) || ( $TTS_text =~ /--D--/ ) ) {
                $Cdash        = '--C--';
                $Ddash        = '--D--';
                @static_check = split( /--C--/, $TTS_text );
                $sc           = 0;
                $sr           = 0;
                foreach (@static_check) {
                    if ( $sc > 0 ) {
                        $static_check[$sc] =~ s/--D-.*//gi;
                        $static_check_lc = lc( $static_check[$sc] );
                        print STDERR
"     Checking For Static Replacement: $static_check[$sc]|$static_check_lc$wav\n";
                        $static_found = 0;
                        if (
                            -e "/var/lib/asterisk/sounds/tts_static/$static_check_lc$wav"
                          )
                        {
                            $CDstatic =
"<audio src='/var/lib/asterisk/sounds/tts_static/$static_check_lc$wav' /> ";
                            $static_found++;
                        }
                        else {
                            if (
                                -e "/var/lib/asterisk/sounds/$static_check_lc$wav"
                              )
                            {
                                $CDstatic =
"<audio src='/var/lib/asterisk/sounds/$static_check_lc$wav' /> ";
                                $static_found++;
                            }
                            else {
                                $firsttwo = substr( $static_check_lc, 0, 2 );
                                if (
                                    -e "/var/lib/asterisk/sounds/tts_static/$firsttwo/$static_check_lc$wav"
                                  )
                                {
                                    $CDstatic =
"<audio src='/var/lib/asterisk/sounds/tts_static/$firsttwo/$static_check_lc$wav' /> ";
                                    $static_found++;
                                }
                            }
                        }
                        if ( $static_found > 0 ) {
                            $CDmatch = "$Cdash$static_check[$sc]$Ddash";
                            $TTS_text =~ s/$CDmatch/$CDstatic/gi;
                            print STDERR
"       Static Replacement Found: $CDmatch|$CDstatic\n";
                            $sr++;
                        }
                    }
                    $sc++;
                }
                $TTS_text =~ s/--C--|--D--//gi;
                print STDERR "\nStatic Replacements Found: $sc|$sr\n";
            }
            $TTS_text =~ s/[^,\.\<\>\'\/\=\_\-\: 0-9a-zA-Z]//gi;
            $TTS_textRAW = $TTS_text;
            $TTS_text =~ s/ /\\ /gi;
            $TTS_text =~ s/\./\\./gi;
            $TTS_text =~ s/\=/\\=/gi;
            $TTS_text =~ s/\</\\</gi;
            $TTS_text =~ s/\>/\\>/gi;
            $TTS_text =~ s/\//\\\//gi;
            $TTS_text =~ s/\n|\r/ /gi;
            $TTS_text =~ s/\'/\\'/gi;
            print STDERR "\nGenerating: $TTS_text - $TTS_voice\n";
`$PATHagi/cepstral_generate.pl --debug --voice=$TTS_voice --dialog=$TTS_text >> $CEPLOGfile `;
            use Digest::MD5 qw(md5_hex);
            $enc     = md5_hex("$TTS_textRAW-$TTS_voice");    # the hash
            $enc_ftl = substr( $enc, 0, 2 );    # first letter of hash
            $TTS_filename_path =
              $PATHsounds . "/tts/" . $enc_ftl . "/tts-" . $enc;
            print STDERR "\nfilename: $TTS_filename_path\n";
            $confirm_entry_prompt = $TTS_filename_path;
            $confirmation         = 0;
            $confirmation_chances = 0;
            $ms_delay             = '6000';

            while ( ( $confirmation_chances < 2 ) && ( $confirmation < 1 ) ) {
                $confirmation_chances++;
                &confirm_entry;
                if ( $ANSWER_confirm > 1 ) {
                    $found_extension      = 'B';
                    $found_priority       = '1';
                    $confirmation_chances = 99;
                    if ($AGILOG) {
                        $agi_string =
                          "account not confirmed: $ANSWER_confirm|$lead_id";
                        &agi_output;
                    }
                }
                if ( ( $ANSWER_confirm > 0 ) && ( $ANSWER_confirm < 2 ) ) {
                    $confirmation = 1;
                }
            }
        }
        $sthA->finish();
    }
    $PADlead_id = sprintf( "%010s", $lead_id );
    while ( length($PADlead_id) > 10 ) { chop($PADlead_id); }
    $YqueryCID    = "Y$CIDdate$PADlead_id";
    $Ynewcallerid = "\"$YqueryCID <$callerid>\"";
    if ($AGILOG) {
        $agi_string =
"account found: $lead_id|$phone_number|$first_name|$last_name|$Ynewcallerid";
        &agi_output;
    }
    $AGI->set_callerid($Ynewcallerid);
    if ( $confirmation > 0 ) {
        $phone_update_SQL      = '';
        $user_update_SQL       = '';
        $uniqueid_address3_SQL = '';
        $title_update_SQL      = '';
        if ( $phone_update =~ /Y/i ) {
            if (   ( length($callerid) > 6 )
                && ( $callerid !~ /unknown|private/i ) )
            {
                $phone_update_SQL = ",phone_number='$callerid'";
            }
            else {
                if ($AGILOG) {
                    $agi_string =
"--  CMLOOKUP vl record failed: Invalid CIDnumber - $callerid|$phone_number";
                    &agi_output;
                }
            }
        }
        if ( $uniqueid_address3 =~ /Y/ ) {
            $uniqueid_address3_SQL = ",address3='$uniqueid'";
        }
        if ( ( length($call_var_title) > 0 ) && ( $title_update =~ /Y/i ) ) {
            $title_update_SQL = ",title='$call_var_title'";
        }
        if ( length($agent_user_id) > 1 ) {
            if ( $agent_id_update =~ /COMMENT/i ) {
                $user_update_SQL = ",comments='$agent_user_id'";
            }
            if ( $agent_id_update =~ /Y/i ) {
                $user_update_SQL = ",user='$agent_user_id'";
            }
        }
        $stmtA =
"UPDATE vicidial_list SET modify_date=NOW() $phone_update_SQL $user_update_SQL $uniqueid_address3_SQL $title_update_SQL where lead_id='$lead_id';";
        $affected_rows = $dbhA->do($stmtA);
        if ($AGILOG) {
            $agi_string =
"--  CMLOOKUP vl record updated: |$affected_rows| $lead_id|$callerid|$phone_number|$first_name|$last_name|$agent_user_id|$call_var_title|$uniqueid|";
            &agi_output;
        }
    }
}
else {
    $sthA->finish();
    $INVCOUNT     = $AGI->get_variable(INVCOUNT);
    $INVCOUNT     = ( $INVCOUNT + 1 );
    $INVCOUNT_set = $AGI->set_variable( 'INVCOUNT', "$INVCOUNT" );
    if ($AGILOG) { $agi_string = "account not found: $INVCOUNT"; &agi_output; }
}
$AGI->stream_file('sip-silence');
$AGI->stream_file('sip-silence');
$AGI->stream_file('sip-silence');
if ($AGILOG) {
    $agi_string =
"exiting the cm_lookup.agi app, transferring call to $found_extension @ $context + $found_priority";
    &agi_output;
}
print "SET CONTEXT $context\n";
$result = <STDIN>;
checkresult($result);
print "SET EXTENSION $found_extension\n";
$result = <STDIN>;
checkresult($result);
print "SET PRIORITY $found_priority\n";
$result = <STDIN>;
checkresult($result);
exit;

sub checkresult {
    $pass = 0;
    $fail = 0;
    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 = '';
}

sub confirm_entry {
    $interrupt_digit = '';
    $audio_file      = "$confirm_entry_prompt";
    if ( $language =~ /es/ ) {
        $file_extension_gsm = '.gsm';
        $file_extension_wav = '.wav';
        $audio_suffix       = '_es';
        if (
            ( -e ("$PATHsounds/$audio_file$audio_suffix$file_extension_gsm") )
            || (
                -e ("$PATHsounds/$audio_file$audio_suffix$file_extension_wav") )
          )
        {
            $donothing = 1;
        }
        else { $audio_suffix = ''; }
    }
    else { $audio_suffix = ''; }
    $interrupt_digit = $AGI->stream_file( "$audio_file$audio_suffix", '12' );
    print STDERR "interrupt_digit |$interrupt_digit|\n";
    $digits_being_entered = 1;
    $ANSWER_confirm       = '';
    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; }
        $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("$ms_delay") )
              ;    # wait 10 seconds for input or until the pound key is pressed
            if ( $digit =~ /\d/ ) {
                $ANSWER_confirm = "$ANSWER_confirm$digit";
                print STDERR
                  "digit |$digit|     ANSWER_confirm |$ANSWER_confirm|\n";
                undef $digit;
            }
            else {
                $digits_being_entered = 0;
            }
            $digit_loop_counter++;
        }
    }
    $ANSWER_confirm =~ s/\D//gi;
    if ($ANSWER_confirm) {
        print STDERR "digit |$digit|     ANSWER_confirm |$ANSWER_confirm|\n";
    }
}
