#!/bin/bash
export PATH=/usr/sbin:/sbin:$PATH
export LD_PRELOAD=/lib/libc.so.6
#timings for sar
end_time=$(date +%H:%M:%S)
start_time=$(awk 'BEGIN { print strftime("%H:%M:%S",systime()-60*60); exit }')
temp_file=$(mktemp /tmp/report_tmp.XXXXXX)
audio_report_file=/tmp/Audio_Report.tar.gz
app_dir=/AvayaDir/SIP/application
AVAYA_PATH_APP="/AvayaDir/SIP/application"
AVAYA_VAR_LOG="/var/log"
AVAYA_TMP_LOG="/tmp/logs"
AVAYA_PATH_DHCP="/var/run/dhcp"
AVAYA_PATH_DHCP_TMP="/tmp"
echo "phone-report in progress"

zip_file=phone_report_${USER}.tar.gz

sds_files="/var/log/* /tmp/logs/avaya_phone.log /tmp/logs/oldlogsdontouch* $app_dir/*.txt $app_dir/LogFiles/EndpointLog*.txt $app_dir/*.xml $audio_report_file"
sds_files_small="/tmp/logs/avaya_phone.log /tmp/logs/oldlogsdontouch* $app_dir/*.txt $app_dir/LogFiles/EndpointLog*.txt $app_dir/*.xml"

report_print()
{
    if [ -z "$report_file" ]; then
        echo $*
    else
        echo $* >>$report_file
    fi
}

run_command()
{
    desc=$1

    shift
    command=$*
    report_print
    report_print "############## Category : $category  ##############"
    report_print "############## Description : $desc  ##############"
    report_print "############## Command : $command  ##############"
    report_print "############## Output ##############"
    report_print
    if [ -z "$report_file" ]; then
        $command 2>&1
    else
        $command 2>&1 | cat >> $report_file
    fi
    report_print
    report_print "############## End ##############"
}

display_reset_cause()
{
	echo " " >> $report_file
	echo "#######################    Kernel Reset Cause    ###########################" >> $report_file
	echo "##  Possible STICKYBITS register values:                                  ##" >> $report_file
	echo "##    0x00000080: Plug-out                                                ##" >> $report_file
	echo "##    0x00000480: Linux / application reboot                              ##" >> $report_file
	echo "##    0x00000880: HW watchdog reboot                                      ##" >> $report_file
	echo "## From /tmp/logs/avaya_phone.log (if empty - check in /var/log/*):       ##" >> $report_file
	cat  /tmp/last_reset_cause.txt >> $report_file 
	echo "############################################################################" >> $report_file
}

system_command()
{
    category=System
    run_command 'System Data' 'date'
    run_command 'System Identification' 'uname -a'
    run_command 'System uptime information' 'uptime'
    run_command 'CPU Information' 'cat /proc/cpuinfo'
    run_command 'Memory information' 'free'
    run_command 'Memfree' 'cat /proc/meminfo'
    run_command 'Virtual memory statistics' 'cat /proc/vmstat'
    run_command 'Mounted FS information and Usage' 'df -h'
    run_command 'Loaded modules' 'lsmod'
    run_command 'System interrupts' 'cat /proc/interrupts'
    run_command 'Heartbeat status' 'cat /tmp/heartbeat.txt'
    run_command 'Platform Configuration' 'cat /nvdata/platform.cfg'
    run_command 'Process status' 'ps -eLo pid,tid,class,rtprio,ni,pri,psr,pcpu,stat,wchan:14,comm'
    run_command 'TOP Status' 'top -n 1 -b'
    run_command 'File NR' 'cat /proc/sys/fs/file-nr'
    run_command 'Semaphore and Queue status' 'ipcs'
    run_command 'System boot log' 'dmesg'
    run_command 'GPIO State Information' 'cat /sys/kernel/debug/gpio'
    run_command 'Core dump files' 'ls -al /data/crash/'
    run_command 'application directory' 'ls -al /AvayaDir/SIP/application'
    display_reset_cause
    ls /tmp/logs
# Uncomment when application creates a handler for SIGINT
#    kill -2 $(ps x | grep "$app_dir/96" | grep -v gre | awk '{print $1}')
}

network_command()
{
    category=Network
    run_command 'Configured network interfaces information' 'ifconfig -a'
    run_command 'Configured Routing table' 'route -n'
    run_command 'Configured DNS servers information' 'cat /etc/resolv.conf'
    run_command 'Static Host configuration' 'cat /etc/hosts'
    run_command 'Network statistics' 'netstat -an'
    run_command 'Configured Firewall rules' 'iptables -L -n'
    run_command 'Netowrk interface statistics' 'ethtool -S eth0'
    run_command 'Network configuration ' 'ethtool eth0'
    echo "################### DHCP Information ##################" >> $report_file;
    for file in /var/run/dhcp/*; do echo === $file === >>$report_file ;cat $file >> $report_file; done
    for file in /tmp/dhcp* ; do echo ==== $file ====  >> $report_file; cat $file  >> $report_file; done
}

audio_command()
{
    category=Audio
    run_command 'Audio statistics EPT buffer statistics : buffers' 'cat /proc/ept/bufErrStats'
    run_command 'Audio statistics EPT Active audio codecs'  'cat /proc/ept/activeAudioCodec'
    run_command 'Audio statistics EPT dev' 'cat /proc/ept/stream_dev'
    run_command 'Audio statistics EPT pve stats ' 'cat /proc/ept/pvestats'
    run_command 'Audio statistics EPT pve statate ' 'cat /proc/ept/pvestate'
    run_command 'Audio statistics EPT RTP stats' 'cat /proc/ept/rtpstats'
    run_command 'Audio statistics EPT Audio Sync' 'cat /proc/ept/audsync'
    run_command 'Audio statistics EPT Message Pool' 'cat /proc/ept/msgpool'
#    run_command 'Audio statistics EPT HW CryptoAuthEnable' 'cat /proc/ept/hwCryptoAuthEnable'
#    run_command 'Audio statistics EPT HW CryptoCipherEnable' 'cat /proc/ept/CryptoCipherEnable'
    run_command 'Audio statistics EPT NET stats' 'cat /proc/ept/netstats'
    run_command 'Audio statistics EPT Perfsum' 'cat /proc/ept/perfsum'
    run_command 'Audio statistics AMXR' 'cat /proc/amxr'
    run_command 'Audio statistics DMA Channels' 'cat /proc/dma/channels'
    run_command 'Audio statistics DMA Devices' 'cat /proc/dma/devices'
    run_command 'Audio statistics DMA Mem Type' 'cat /proc/dma/mem-type'
    run_command 'Audio statistics HAL Audio' 'cat /proc/halaudio'
    run_command 'Audio statistics APM amp0' 'cat /proc/apm/apm0'
    run_command 'Audio statistics APM amp1' 'cat /proc/apm/apm1'
    run_command 'Audio statistics PCM pcm0 ' 'cat /proc/pcm/pcm0'
#    run_command 'Audio statistics PXCON' '/bin/pxcon /AvayaDir/lib/AudioConfiguration.pxcon'
}

threads_command()
{
    category=Threads
    if [ -f $app_dir/96x1*.bin ]; then
        pid_of_app=$(ps ax | grep "$app_dir/96x1" | grep -v gre | awk '{print $1}')
    elif [ -f $app_dir/sparkbcm*.bin ]; then
        pid_of_app=$(ps ax | grep "$app_dir/sparkbcm" | grep -v gre | awk '{print $1}')
    fi
    if [ -n "$pid_of_app" ]; then
        run_command 'Application Threads' "top -n 1 -bH -p$pid_of_app"
    else
        run_command 'Application Threads' 'echo Application not running'
    fi
}

help()
{
    echo "$0 - Utility to prepare and output phone system information"
    echo "Options:"
    echo "-l <BYTES> - Limit report file size"
    echo "-a - Enable audio information. Disabled by default"
    echo "-h - This help"
}

list_modules()
{
    if [ $sys_flag -eq 1 ]; then
        echo "Module : System Information enabled"
    fi
    if [ $net_flag -eq 1 ]; then
        echo "Module : Network Information enabled"
    fi
    if [ $audio_flag -eq 1 ]; then
        echo "Module : Audio Information enabled"
    fi
    if [ $threads_flag -eq 1 ]; then
        echo "Module : Threads Information enabled"
    fi
}

set_default_flags()
{
    sys_flag=1
    net_flag=1
    audio_flag=0
    threads_flag=1
    report_file=$(mktemp -t)
}

run_commands_by_flags()
{
    if [ "$sys_flag" == "1" ]; then
        echo "Generating report for System information"
        system_command
    fi
    if [ "$net_flag" == "1" ]; then
        echo "Generating report for Network information"
        network_command
    fi
    if [ "$audio_flag" == "1" ]; then
        echo "Generating report for Audio information"
        audio_command
    fi
    if [ "$threads_flag" == "1" ]; then
        echo "Generating report for Threads information"
        threads_command
    fi
    echo "All reports have been generated"
}

func_stop_start_tar()
{
    sleep 10
    pid_of_tar=$(ps axo pid,ppid,comm | grep $$ | grep -v grep | grep "tar" | awk '{print $1}')
    
    if [ -z "$pid_of_tar" ]; then
        exit
    fi	
    
    while test -d /proc/$pid_of_tar; do	
        #Send SIGSTOP $pid_of_phone_report
        kill -s 19 $pid_of_tar 2>/dev/null

        sleep 3		
        #Send SIGCONT $pid_of_tar
        kill -s 18 $pid_of_tar 2>/dev/null
        
        sleep 10
    done
}

zip_files()
{
    echo "Generating Avaya Phone report archive"
    date=$(date +%k%M%d%m%g|sed 's/ //')
    run_commands_by_flags
    mv $report_file /tmp/REPORT.txt
    if [ $audio_flag -eq 1 ]; then
        echo "Packaging audio information into $audio_report_file ..."
        sleep 3 ## wait enough time for all files to finish writing
        tar -cvzf $audio_report_file /tmp/REPORT.txt /tmp/logs/96x1_dump /tmp/logs/avaya_phone.log /tmp/knllog.txt
        rm -rf /tmp/REPORT.txt /tmp/report_* /tmp/tmp.* /tmp/knllog.txt
        echo "Done."
        exit 0
    fi
    temp_file=$(mktemp -t)

    file_list=$(find $sds_files -perm -0004 -type f 2>/dev/null)
    # We need to pause the "tar" process, to prevent a very high CPU usage in case than 
    # the phone-report-user script is invoked through the SSH. 
    # Function func_stop_start_tar() is called into forked process for stopping and continuation work of the tar command, 
    # by sending signals SIGSTOP and SIGCONT.
    func_stop_start_tar&
    if [ -r "${AVAYA_PATH_APP}/config.xml"] ; then
        file_list="$file_list ${AVAYA_PATH_APP}/config.xml"
    fi

    if [ -r "${AVAYA_PATH_APP}/configcache.xml" ] ; then
        file_list="$file_list ${AVAYA_PATH_APP}/configcache.xml"
    fi

	file_list="$file_list ${AVAYA_VAR_LOG}/*"
	file_list="$file_list ${AVAYA_TMP_LOG}/*"
	
    echo tar -C /tmp -zcvf $temp_file $file_list REPORT.txt
    if ! tar -C /tmp -zcvf $temp_file $file_list REPORT.txt >/dev/null 2>&1; then
        echo "Error: Failed to prepare /tmp/$zip_file archive"
        exit 1
    fi

    local size=$(ls  -1 -l $temp_file | awk '{print $3}')
    if [ ! -z "$total_size" ] && [ $size -gt $total_size ]; then
        file_list=$(find $sds_files_small -perm -0004 -type f 2>/dev/null)

        report_print "!!!!!!!!!!!! FILES WERE REMOVED DUE TO SIZE LIMITATIONS!!!!!!!!!!!!!!!!!!!!!!!!!!"

        rm -rf $temp_file
        if ! tar -C /tmp -zcvf $temp_file $file_list REPORT.txt >/dev/null 2>&1; then
           echo "Error: Failed to prepare /tmp/$zip_file archive"
           exit 1
        fi
    fi

    echo "Avaya Phone report archive have been generated"
    echo "Archive name on Avaya Phone : /tmp/$zip_file"

    if [ -f /tmp/$zip_file ]; then
        mv /tmp/$zip_file /tmp/$zip_file.bak
    fi
    mv $temp_file /tmp/$zip_file
    rm -rf /tmp/REPORT.txt /tmp/SAR_ALL_REPORT.txt
}

args=`getopt -o hakimcl:  -n $0 -- "$@"`

if [ $? != 0 ] ; then echo "Error parsing cmd args" >&2 ; usage ;exit 1 ; fi

set_default_flags

eval set -- "$args"

while true
do
case $1 in
    -h )
        help
        exit 1
        ;;
    -a )
        audio_flag=1
        shift
        ;;
    -l)
        total_size=$2
        shift 2
        ;;
    --)
        break
        ;;
    *  )
        echo "No such option: $1"
        help
        exit 1
        ;;
  esac
done

zip_files