#!/usr/bin/env bash
# VICIfast Research, Report 01: The Two Bottlenecks Inside a Busy VICIdial Server
# Load rig (§7.2). FOR A THROWAWAY TEST SERVER, NOT A LIVE FLOOR. Read it before you run it.
# Creates the rig on a fresh VICIdial server: a fake carrier LOADSINK (prefix 4455, to the fake carrier only), campaign LOADTEST,
# list 99001 with 300k fake 555 numbers, NAG agents LT001.. with WebRTC phones 9101.., and raises max trunks and CPS.
# Changes the server? YES: adds a carrier, a campaign, a list, users and phones, and changes the server row. Throwaway server only.
# It copies user 6666 and phone 6666 (a WebRTC phone) as templates: change those ids for your server.
# AMI-wall rig 2026-10-23, on the test dialer (all-in-one, throwaway). Re-runnable.
# Creates: carrier LOADSINK (prefix 4455 -> fake carrier box only), campaign LOADTEST (the 10-15 rig's
# OUTBOUND settings: RATIO, AMD 8369, ALLFORCE, 35 s timeout, 5 s drop to 8307), list 99001 with 300k
# fake 555 leads, users LT001..LT024 + WebRTC phones 9101..9124. Raises trunks/CPS.
set -euo pipefail
SINK=${SINK:?set SINK to the fake carrier IP}; NAG=${NAG:-48}
B=/root/vf-lt; mkdir -p $B; chmod 700 $B
DB=$(awk -F'=> *' '/^VARDB_database/{print $2}' /etc/astguiclient.conf); SIP=$(awk -F'=> *' '/^VARserver_ip/{print $2}' /etc/astguiclient.conf)
M="mysql $DB"
[ -s $B/creds ] || { umask 077; printf 'AGENT_PASS=%s\nPHONE_PASS=%s\nSIP_SECRET=%s\n' "$(openssl rand -hex 8)" "$(openssl rand -hex 8)" "$(openssl rand -hex 12)" > $B/creds; }
. $B/creds
ACCT="[loadsink]
type=aor
contact=sip:${SINK}:5060
qualify_frequency=0

[loadsink]
type=endpoint
transport=transport-udp
context=trunkinbound
disallow=all
allow=ulaw
aors=loadsink
dtmf_mode=rfc4733
direct_media=no
rtp_symmetric=yes
force_rport=yes
rewrite_contact=yes
rtp_timeout=30
rtp_timeout_hold=60
timers=no

[loadsink]
type=identify
endpoint=loadsink
match=${SINK}"
DP='exten => _4455X.,1,AGI(agi://127.0.0.1:4577/call_log)
exten => _4455X.,n,Dial(PJSIP/${EXTEN:4}@loadsink,,To)
exten => _4455X.,n,Hangup()'
q(){ printf '%s' "$1" | sed "s/'/''/g"; }
$M -e "DELETE FROM vicidial_server_carriers WHERE carrier_id='LOADSINK';
  INSERT INTO vicidial_server_carriers (carrier_id,carrier_name,registration_string,template_id,account_entry,protocol,globals_string,dialplan_entry,server_ip,active,carrier_description,user_group)
  VALUES ('LOADSINK','Load test fake carrier','','--NONE--','$(q "$ACCT")','PJSIP','','$(q "$DP")','$SIP','Y','LOAD TEST 2026-10-23 throwaway box','---ALL---')"
$M -e "DELETE FROM vicidial_campaigns WHERE campaign_id='LOADTEST';
  INSERT INTO vicidial_campaigns (campaign_id,campaign_name,active,dial_method,auto_dial_level,dial_timeout,dial_prefix,manual_dial_prefix,
    campaign_vdad_exten,campaign_recording,campaign_rec_filename,am_message_exten,amd_send_to_vmx,cpd_amd_action,amd_type,
    drop_call_seconds,drop_action,safe_harbor_exten,available_only_ratio_tally,hopper_level,use_auto_hopper,auto_trim_hopper,
    local_call_time,waitforsilence_options,routing_initiated_recordings,dial_statuses,lead_order,campaign_cid,campaign_allow_inbound,next_agent_call)
  VALUES ('LOADTEST','Load test 2026-10-23','Y','RATIO','0',35,'4455','4455','8369','ALLFORCE','CAMPAIGN_TINYDATE_CUSTPHONE','vm-goodbye','N','DISABLED','AMD',
    5,'MESSAGE','8307','N',6000,'N','N','24hours','2000,2,30','Y',' NEW -','DOWN','5555550100','N','longest_wait_time');
  INSERT IGNORE INTO vicidial_campaign_stats (campaign_id) VALUES ('LOADTEST');
  DELETE FROM vicidial_lists WHERE list_id=99001;
  INSERT INTO vicidial_lists (list_id,list_name,campaign_id,active) VALUES (99001,'Load test leads','LOADTEST','Y');"
if [ "$($M -N -e "select count(*) from vicidial_list where list_id=99001")" != 300000 ]; then
  $M -e "DELETE FROM vicidial_list WHERE list_id=99001"
  awk 'BEGIN{for(i=0;i<300000;i++) printf "99001\tNEW\t1\t555%03d%04d\t-5.00\tN\tLT\tLoad\t2026-10-23 00:00:00\tLT%06d\n", 200+int(i/10000), i%10000, i}' > $B/leads.tsv
  shuf --random-source=<(yes) $B/leads.tsv > $B/leads-shuf.tsv
  mysql --local-infile=1 $DB -e "LOAD DATA LOCAL INFILE '$B/leads-shuf.tsv' INTO TABLE vicidial_list (list_id,status,phone_code,phone_number,gmt_offset_now,called_since_last_reset,first_name,last_name,entry_date,vendor_lead_code)"
fi
$M -e "DELETE FROM vicidial_users WHERE user LIKE 'LT0%'; DELETE FROM phones WHERE extension BETWEEN '9101' AND '9199';"
for n in $(seq 1 $NAG); do
  u=$(printf 'LT%03d' $n); ext=$((9100+n))
  $M -e "CREATE TEMPORARY TABLE tu ENGINE=MyISAM AS SELECT * FROM vicidial_users WHERE user='6666';
    UPDATE tu SET user_id=0, user='$u', pass='$AGENT_PASS', full_name='Load agent $n', user_level=1, vdc_agent_api_access='1', user_group='ADMIN';
    INSERT INTO vicidial_users SELECT * FROM tu;
    CREATE TEMPORARY TABLE tp ENGINE=MyISAM AS SELECT * FROM phones WHERE extension='6666';
    UPDATE tp SET extension='$ext', dialplan_number='$ext', voicemail_id='$ext', login='$ext', pass='$PHONE_PASS',
      conf_secret='$SIP_SECRET', fullname='Load phone $n', server_ip='$SIP', outbound_cid='5555550100';
    INSERT INTO phones SELECT * FROM tp;"
done
$M -e "UPDATE servers SET max_vicidial_trunks=800, outbound_calls_per_second=60, rebuild_conf_files='Y' WHERE server_ip='$SIP'"
$M -t -e "select server_ip,max_vicidial_trunks,outbound_calls_per_second from servers;
  select carrier_id,server_ip,active from vicidial_server_carriers;
  select campaign_id,active,dial_method,auto_dial_level,dial_prefix,campaign_recording,campaign_vdad_exten from vicidial_campaigns;
  select count(*) leads, count(distinct phone_number) uniq, min(phone_number), max(phone_number) from vicidial_list where list_id=99001;
  select count(*) phones from phones where extension between '9101' and '9199';
  select count(*) users from vicidial_users where user like 'LT0%';"
