#!/bin/bash

[ ! -f launch.config.perso ] && echo "launch.config.perso not found" && exit 1

FLEXISIP=flexisip
SIPP=sipp
NB_USERS=1000
IP=`cat /etc/hosts | grep "sip.example.org" | grep "sip-auth.example.org" | grep "relayed-auth.example.org" | grep "relayed.example.org" | grep -e "^[^#]" | awk -F'\t' '{print $1}'`
[ -z $IP ] && echo "ERROR: sip.example.org not found in /etc/hosts" && exit
PROXY=sip.example.org
REGISTER_PORT=5070
USERS_PORT=5063
INVITER_PORT=5064

# Import configuration
FOLDER=multi
SERIALIZER="$1"


[ ! -f $FOLDER/launch.config ] && echo "config file not found : "$FOLDER/launch.config"" && exit
FLEX_OPTIONS="$FLEX_OPTIONS --configfile $FOLDER/flexisip_$SERIALIZER.conf --port 5060"
. $FOLDER/launch.config

[ ! -f $FOLDER/flexisip_$SERIALIZER.conf ] && echo "Serializer $SERIALIZER not found, use `ls $FOLDER/flexisip*.conf`" && exit

SIPP_COMMONS="$SIPP_COMMONS -i $IP -trace_err"
REG_OPTIONS="$REG_OPTIONS -p 5070 -m `echo "1+$NB_USERS"|bc` $SIPP_COMMONS -inf authentication.csv"
REG_INVITER_OPTIONS="$REG_INVITER_OPTIONS -p 5064 -m 1 $SIPP_COMMONS -nd"
MULTI_OPTIONS="$MULTI_OPTIONS -m $NB_USERS -p 5064 $SIPP_COMMONS"
UAS_OPTIONS="$UAS_OPTIONS -p 5063 -bg $SIPP_COMMONS -mi $IP -mp 15000 -rtp_echo"

echo "NB_USERS=$NB_USERS"
echo "LD_LIBRARY_PATH=$LD_LIBRARY_PATH"

# Accept core dumps
ulimit -c unlimited

# Open many file descriptors
ulimit -n 65000


CMD_UAS="$SIPP -sf uas.xml $UAS_OPTIONS"
echo -e "\n\033[1mStart users listening: $CMD_UAS \033[0m"
$CMD_UAS 2>&1 > /dev/null

CMD_FLEXISIP="$FLEXISIP $FLEX_OPTIONS"
echo -e "\n\033[1mPlease start flexisip: $CMD_FLEXISIP \033[0m"
$CMD_FLEXISIP 2>&1 > flexisip.log &
sleep 2s


#CMD_REG_USERS="$SIPP $PROXY -sf register_users.xml $REG_OPTIONS"
#echo -e "\n\033[1mRegister users $CMD_REG_USERS \033[0m (never authenticated)"
#$CMD_REG_USERS



# Allow killing
function onexit() {
 echo -e "\e[0;31mKilling everyone \033[0m"
 killall flexisip 2>/dev/null
 killall sipp 2>/dev/null

 LOGS=logs/"$FOLDER"_`date '+%s'`
 LOGS_TO_SAVE=$FOLDER"/*.log *.log core"
 mkdir -p $LOGS
 mv $LOGS_TO_SAVE $LOGS

 exit
}
set -o errtrace 
trap onexit 1 2 3 15 ERR

CMD_REGISTER_MULTI_USERS="$SIPP $PROXY -sf $FOLDER/register_multi_noauth.xml $MULTI_OPTIONS"
echo -e "\n\033[1mStart registering users with many contacts: $CMD_REGISTER_MULTI_USERS \033[0m"
while [ true ]
do
  $CMD_REGISTER_MULTI_USERS
done

onexit 
