#! /bin/bash
#
if [ -z "$toolsPath" ] ;then
 #    toolsPath=/usr/fb/tests/sipp_dev
	toolsPath=/usr/bin/
fi

mkdir -p /usr/fb/tests/sipp_xml/logs/
doSudo="/usr/bin/sudo"
export PATH=$PATH:${toolsPath}

pidfile=/var/run/dotest.pid
if [ -e $pidfile ]; then
	pid=`cat $pidfile`
	if ${doSudo} kill -0 &>1 > /dev/null $pid; then
	echo "Already running"
	exit 1
else
	${doSudo} rm $pidfile
	fi
fi
${doSudo} touch $pidfile && ${doSudo} chown www-data $pidfile
${doSudo} echo $$ > $pidfile


# Signal-Handler definieren
function handler()
{
  if [ -z "$killed" ] ;then
    killed=1
    touch "${basis}.syntaxerror"
  else
    if test -e "$basis.post.xml" ;then
        if test -e "${basis}.post.xml" ;then
            ${doSudo} rm ${basis}.post.xml*.log 2>/dev/null
            ${doSudo} rm ${basis}.post.xml*.messages 2>/dev/null
            ${doSudo} rm ${basis}.post.xml*.shortmessages 2>/dev/null
            ${doSudo} rm ${basis}.post.xml*.errors 2>/dev/null
            ${doSudo} rm ${basis}.post.xml*.syntaxerror 2>/dev/null
            ${doSudo} rm ${basis}.post.xml*.wav 2>/dev/null
            ${doSudo} rm ${basis}.post.xml*.dtmf 2>/dev/null
            echo "====================== start post config part ($basis.post.xml) ==================="
            
            ${doSudo} ${toolsPath}/sipp $ip -sf ${basis}.post.xml -mp 7700 -silent -t $mode -i $local_ip -mi $local_ip -p $port2 \
                -trace_dtmf -trace_msg -trace_shortmsg -trace_logs -trace_err -pause_msg_ign -m 1 -users 1 \
                -s "4711" >/dev/null 2>/dev/null
        fi
    fi
    exit 1
  fi
}

function startTest()
{

    if test -e "${1}.xml" ;then
        sleep 1

        ${doSudo} rm ${1}*.log 2>/dev/null
        ${doSudo} rm ${1}*.messages 2>/dev/null
        ${doSudo} rm ${1}*.shortmessages 2>/dev/null
        ${doSudo} rm ${1}*.errors 2>/dev/null
        ${doSudo} rm ${1}*.syntaxerror 2>/dev/null
        ${doSudo} rm ${1}*.wav 2>/dev/null
        ${doSudo} rm ${1}*.dtmf 2>/dev/null
        echo "====================== start $1 part ==================="


        ${doSudo} ${toolsPath}/sipp $ip -sf ${1}.xml -mp 7700 -silent -t $mode -i $local_ip -mi $local_ip -p $port2 \
            -trace_dtmf -trace_msg -trace_shortmsg -trace_logs -trace_err -pause_msg_ign -m 1 -users 1 \
            -s "4711" 
#>/dev/null 2>/dev/null

        sleep 1
    fi
}

# Signal-Handler "handler()" mit Signal SIGUSR1 verbinden
trap handler SIGINT

getipvalues() {
    IP_ADDRESS=`/sbin/ifconfig  eth0 | grep 'inet addr:\|inet Adresse:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}'`
    IP_BCAST=`/sbin/ifconfig  eth0| grep 'inet addr:\|inet Adresse:'| grep -v '127.0.0.1' | cut -d: -f3 | awk '{ print $1}'`
    IP_MASK=`/sbin/ifconfig  eth0 | grep 'inet addr:\|inet Adresse:'| grep -v '127.0.0.1' | cut -d: -f4 | awk '{ print $1}'`
    IP_GW=`/sbin/route -n|grep -m 1 '^0.0.0.0'| awk '{print $2}'`
}

usage () {
    echo >&2 "Usage: $0 [-f file] [-n number to dial] [-b basenumber to dial] [-B basenumber2 to dial] [-l local_ip] [-i ip-address] [-p port] [-P port2] [-m ip-mode] [-d] [-t] [-a]"
    echo >&2 "ip-mode is one of the following:"
    echo >&2 "  - u1: UDP with one socket (default),"
    echo >&2 "  - un: UDP with one socket per call,"
    echo >&2 "  - ui: UDP with one socket per IP address The IP addresses must be defined in the injection file."
    echo >&2 "  - t1: TCP with one socket,"
    echo >&2 "  - tn: TCP with one socket per call,"
    echo >&2 "  - l1: TLS with one socket,"
    echo >&2 "  - ln: TLS with one socket per call"
    echo >&2 " "
    echo >&2 "basenumber is used for destination who simulates errorcauses. NUmber dialed is basnumbr+errorcause which is three digits long"
    echo >&2 " "
    echo >&2 "-a automatic don't wait for keys"
    echo >&2 "-r resume tests, continue all with untested" 
    echo >&2 "-d call less to show sip messages"
    echo >&2 "-g main group to test"
    echo >&2 "-G sub group to test"
    echo >&2 "-t direct testing don't call rec.xml files"
    exit 1
}

while getopts "ab:B:df:g:G:i:l:m:n:p:P:rwt?h" o
  do case "$o" in
  a)   automatic=1;;
  b)   basenumber="$OPTARG";;
  B)   basenumber2="$OPTARG";;
  f)   file="$OPTARG";;
  g)   maingroup="$OPTARG";;
  G)   subgroup="$OPTARG";;
  n)   dest="$OPTARG";;
  i)   ip="$OPTARG";;
  m)   mode="$OPTARG";;
  l)   local_ip="$OPTARG";;
  d)   details=1;;
  p)   port="$OPTARG";;
  P)   port2="$OPTARG";;
  r)   resume="true";;
  t)   direct_testing=1;;
  h) usage;;
  ?) usage;;
  [?]) usage;;
  esac
done
shift $((OPTIND-1))

if [ -z "$basenumber" ] ;then
    basenumber=
fi

if [ -z "$basenumber2" ] ;then
    basenumber2=
fi

if [ -z "$maingroup" ] ;then
    maingroup="0 1 2 3 4 5 6 7 8 9"
fi

if [ -z "$subgroup" ] ;then
    subgroup="0 1 2 3 4 5 6 7 8 9"
fi

if [ -z "$file" ] ;then
    file=""
        for j in $maingroup ;do
	        for i in $subgroup ;do
	            file="$(echo $file;ls $j.$i.*.xml 2>/dev/null | grep -v "rec.xml" | grep -v "post.xml" | grep -v "pre.xml" | sort -n  -t. -k 3)"
	        done
	    done
    if [ "$resume" == "true" ]; then
    	resumefiles=""
    	for myfile in $(echo $file); do
    		 if [ ! -e "${myfile%%.xml}.ok" -a ! -e "${myfile%%.xml}.fail" ]; then
    		 	resumefiles=$resumefiles" "$myfile
    		 fi 
    	done
    	file=$resumefiles
    	if [ -z "$file" ]; then echo "There are no tests to resume" && exit 1;fi
    fi
fi

if [ -z "$dest" ] ;then
    dest=1998
    #dest=221998
fi

if [ -z "$ip" ] ;then
	iface=$(LC_ALL=C route -n | grep 0.0.0.0 | grep UG | awk -F " " '{print $8}')
	ip=$(LC_ALL=C ifconfig $iface | grep inet\ addr | awk -F ":" '{print $2}' | sed s/\ .*//g)
    #ip="10.0.0.130"
fi

if [ -z "$mode" ] ;then
    mode="tn"
fi

if [ -z "$port" ] ;then
    port="6061"
fi

if [ -z "$port2" ] ;then
    port2="6062"
fi

if [ -z "$local_ip" ] ;then
    getipvalues
    local_ip=$IP_ADDRESS
fi

echo $ip,$local_ip

#for i in $file;do echo $i;done
#echo press return to continue ...
#read dummy
startTest prepare

for i in $file; do
    if test -e "$i" ;then
        basis=$(basename ${i} ".xml")
	exec &>/usr/fb/tests/sipp_xml/logs/test-$i
        startTest restore

        ${doSudo} killall -9 sipp 2>/dev/null
        ${doSudo} killall -9 dumppcap 2>/dev/null
        
#        for j in $(ls /proc | grep -E "[0-9].*"); do
#            if test -e "/proc/${j}/cmdline" ;then
#                if grep -q "S2M" /proc/${j}/cmdline ;then
#                    sudo kill -9  $j
#                fi
#            fi  
#        done
        
 	echo $basis > $(pwd)/logs/basis       

        echo "====================== start test $basis ==================="
        echo "===" $(grep "scenario name=" ${i} | sed -e "s/.*scenario name=\"\(.*\)\".*/\1/")
        echo "============================================================"
        echo
        echo $(grep "<\!-- :" ${i} | sed -e "s/.*:\(.*\):.*/\1/" | sed -e "s/#basenumber2#/${basenumber2}/" | sed -e "s/#basenumber#/${basenumber}/")
        
        cmd=$(grep "<\!-- +" ${i} | sed -e "s/.*+\(.*\)+.*/\1/")
	
        ${doSudo} echo ${cmd} > command.tmp
        . ./command.tmp
        ${doSudo} rm command.tmp
        
        question=$(grep "<\!-- #" ${i} | sed -e "s/.*#\(.*\)#.*/\1/")
        if [ ! -z "$question" ] ;then
            if [ -z "$automatic" ] ;then
            	    echo $question
	                echo press return to continue ...
	                read dummy
	                #read -n1 -p "Hit any key to continue. "
            	fi
        fi
        
        ${doSudo} rm ${basis}*.log 2>/dev/null 
        ${doSudo} rm ${basis}*.messages 2>/dev/null
        ${doSudo} rm ${basis}*.shortmessages 2>/dev/null
        ${doSudo} rm ${basis}*.errors 2>/dev/null
        ${doSudo} rm ${basis}*.syntaxerror 2>/dev/null
        ${doSudo} rm ${basis}*.wav 2>/dev/null
        ${doSudo} rm ${basis}*.dtmf 2>/dev/null
        ${doSudo} rm ${basis}*.fail 2>/dev/null
        ${doSudo} rm ${basis}*.ok 2>/dev/null

        ls ${basis}.*

        if test -e "$basis.pre.xml" ;then
            if test -e "${basis}.pre.xml" ;then
                sleep 1

                ${doSudo} rm ${basis}.pre.xml*.log 2>/dev/null
                ${doSudo} rm ${basis}.pre.xml*.messages 2>/dev/null
                ${doSudo} rm ${basis}.pre.xml*.shortmessages 2>/dev/null
                ${doSudo} rm ${basis}.pre.xml*.errors 2>/dev/null
                ${doSudo} rm ${basis}.pre.xml*.syntaxerror 2>/dev/null
                ${doSudo} rm ${basis}.pre.xml*.wav 2>/dev/null
                ${doSudo} rm ${basis}.pre.xml*.dtmf 2>/dev/null
                echo "====================== start preconfig part ($basis.pre.xml) ==================="
                
                ${doSudo} ${toolsPath}/sipp $ip -sf ${basis}.pre.xml -mp 7700 -silent -t $mode -i $local_ip -mi $local_ip -p $port2 \
                    -trace_dtmf -trace_msg -trace_shortmsg -trace_logs -trace_err -pause_msg_ign -m 1 -users 1 \
                    -s "4711" >/dev/null 2>/dev/null
		preretval=$?


		[ "$preretval" != 0 ] && echo "preconfiguration process failed! exiting now..." && exit 1
                sleep 3
            fi
        fi
        
        if [ -z "$direct_testing" ] ;then
            if test -e "${basis}.rec.xml" ;then
                ${doSudo} rm ${basis}.rec.xml*.log 2>/dev/null
                ${doSudo} rm ${basis}.rec.xml*.messages 2>/dev/null
                ${doSudo} rm ${basis}.rec.xml*.shortmessages 2>/dev/null
                ${doSudo} rm ${basis}.rec.xml*.errors 2>/dev/null
                ${doSudo} rm ${basis}.rec.xml*.syntaxerror 2>/dev/null
                ${doSudo} rm ${basis}.rec.xml*.wav 2>/dev/null
                ${doSudo} rm ${basis}.rec.xml*.dtmf 2>/dev/null
                echo "====================== start receiving part ($basis.rec.xml) ==================="
                
                if grep -q play_pcap_audio ${basis}.rec.xml;then
                    echopar=rtp_receive
                else
                    echopar=rtp_echo
                fi
                
                parameter=$(grep "<\!-- =" ${basis}.rec.xml | sed -e "s/.*[=]\(.*\)[=].*/\1/")
                if [ "$parameter" = "basenumber" ] ;then
                    nrToDial=$basenumber
                elif [ "$parameter" = "basenumber2" ] ;then
                    nrToDial=$basenumber2
                else
                    nrToDial=$dest
                fi

                ${doSudo} ${toolsPath}/sipp $ip -sf ${basis}.rec.xml -mp 7700 -silent -t $mode -i $local_ip -mi $local_ip -p $port2 \
                    -trace_dtmf -trace_msg -trace_shortmsg -trace_logs -trace_err  -pause_msg_ign -m 1 -users 1 \
                    -s "$nrToDial" -$echopar  >/dev/null 2>/dev/null & 

            fi
        fi
        
        if grep -q play_pcap_audio ${i};then
            echopar=rtp_receive
        else
            echopar=rtp_echo
        fi
        
        parameter=$(grep "<\!-- =" ${i} | sed -e "s/.*[=]\(.*\)[=].*/\1/")
        if [ "$parameter" = "basenumber" ] ;then
            nrToDial=$basenumber
        elif [ "$parameter" = "basenumber2" ] ;then
            nrToDial=$basenumber2
        else
            nrToDial=$dest
        fi
        ${doSudo} ${toolsPath}/sipp $ip -sf $i -mp 7500 -silent -t $mode -i $local_ip -mi $local_ip -p $port \
            -trace_dtmf -trace_msg -trace_shortmsg -trace_logs -trace_err  -pause_msg_ign -m 1 \
            -users 1 -s "$nrToDial" -rtp_receive -$echopar

        retval=$?
	echo "#################### $retval ############################"
	#ps fax | grep sipp
        let linecheck=30
        dobreak="0"
        while [ "$dobreak" = "0" ];do
            dobreak="1"
            for j in $(ls /proc | grep -E "[0-9].*"); do
                if test -e "/proc/${j}/cmdline" ;then
                    if grep -q "sipp[0-9]" /proc/${j}/cmdline ;then
                        dobreak="0"
                        let linecheck=$linecheck-1
                        if test $linecheck -le 0; then
                            echo " "
                            echo -n "* $j: "
                            ps -w -o "cmd=" -p $j
                            sudo kill -9  $j
                            sleep 1
                        else
                            echo -n "."
                        fi
                        sleep 1
                    fi
                fi  
            done
        done
        echo " "
        
        sleep 1
#        for j in $(ls /proc | grep -E "[0-9].*"); do
#            if test -e "/proc/${j}/cmdline" ;then
#                if grep -q "S2M" /proc/${j}/cmdline ;then
#                    echo "********************* garbage **********************"
#                    echo -n "* $j: "
#                    ps -w -o "cmd=" -p $j
#                    echo "****************************************************"
#                    sudo kill -9  $j
#                fi
#            fi  
#        done
        
        if [ $retval == 0 ] ;then
            if test -e "${basis}.rec.xml" ;then
                sleep 1
            fi
            if [ -e "${basis}.syntaxerror" ] ;then
                echo "---------------------- test $basis failed (1) ------------------"
                echo ""
                ${doSudo} rm ${basis}*.ok 2>/dev/null
                ${doSudo} touch ${basis}.fail
            else
                echo "++++++++++++++++++++++ test $basis ok ++++++++++++++++++++++"
                echo ""
                ${doSudo} rm ${basis}*.fail 2>/dev/null
                ${doSudo} touch ${basis}.ok
				
		if ! test -e "${basis}.history" ;then
		    ${doSudo} echo "SSRC,Packets,FirstSeq,Ordered,Loss,Jitter Max,Jitter Mean,Delta Max,Skew Max" > "${basis}.history"
		fi
			
		${doSudo} cp ${basis}_*_rtp.log ${basis}_rtp.log 2>/dev/null
		${doSudo} awk -f rtp_stat.awk "${basis}_rtp.log" >> "${basis}.history"
		${doSudo} mv ${basis}_*_rtp.log rtp 2>/dev/null
            fi
        else
            if test -e "${basis}.rec.xml" ;then
                sleep 1
            fi
            echo "---------------------- test $basis failed ------------------"
            echo ""
            ${doSudo} rm ${basis}*.ok 2>/dev/null
            ${doSudo} touch ${basis}.fail
        fi
        
        ${doSudo} mv ${basis}.rec_*_logs.log ${basis}.rec.log 2>/dev/null
        ${doSudo} mv ${basis}.rec_*_messages.log ${basis}.rec.messages 2>/dev/null
        ${doSudo} mv ${basis}.rec_*_shortmessages.log ${basis}.rec.shortmessages 2>/dev/null
        ${doSudo} mv ${basis}.rec_*_errors.log ${basis}.rec.errors 2>/dev/null
        ${doSudo} mv ${basis}.rec_*_dtmf.log ${basis}.rec.dtmf 2>/dev/null
        ${doSudo} mv ${basis}.rec_*.wav ${basis}.rec.wav 2>/dev/null
 
        ${doSudo} mv ${basis}_*_logs.log ${basis}.log 2>/dev/null
        ${doSudo} mv ${basis}_*_messages.log ${basis}.messages 2>/dev/null
        ${doSudo} mv ${basis}_*_shortmessages.log ${basis}.shortmessages 2>/dev/null
        ${doSudo} mv ${basis}_*_errors.log ${basis}.errors 2>/dev/null
        ${doSudo} mv ${basis}_*_dtmf.log ${basis}.dtmf 2>/dev/null
        ${doSudo} mv ${basis}_*.wav ${basis}.wav 2>/dev/null
 
        if test -e "$basis.post.xml" ;then
            if test -e "${basis}.post.xml" ;then
                sleep 1

                ${doSudo} rm ${basis}.post.xml*.log 2>/dev/null
                ${doSudo} rm ${basis}.post.xml*.messages 2>/dev/null
                ${doSudo} rm ${basis}.post.xml*.shortmessages 2>/dev/null
                ${doSudo} rm ${basis}.post.xml*.errors 2>/dev/null
                ${doSudo} rm ${basis}.post.xml*.syntaxerror 2>/dev/null
                ${doSudo} rm ${basis}.post.xml*.wav 2>/dev/null
                ${doSudo} rm ${basis}.post.xml*.dtmf 2>/dev/null
                echo "====================== start post config part ($basis.post.xml) ==================="
                
                ${doSudo} ${toolsPath}/sipp $ip -sf ${basis}.post.xml -mp 7700 -silent -t $mode -i $local_ip -mi $local_ip -p $port2 \
                    -trace_dtmf -trace_msg -trace_shortmsg -trace_logs -trace_err -pause_msg_ign -m 1 -users 1 \
                    -s "4711" >/dev/null 2>/dev/null

                sleep 3
            fi
        fi

        ${doSudo} chmod uag+rw ${basis}*
        
        if [ ! -z "$details" ] ;then
            echo press return to continue ...
            read dummy
            ${doSudo} less ${basis}.messages
        fi
    else
        echo $file did not exist
    fi
done
       
startTest restore
