#!/bin/sh
export PATH=/usr/sbin:/sbin:$PATH
export LD_PRELOAD=/lib/libc.so.6

if [ -n "$(cat /proc/cpuinfo | grep -i dvf99)" ]; then
    PLATFORM_DVF99=1
elif [ -n "$(cat /proc/cpuinfo | grep -i dvf101)" ]; then
    PLATFORM_DVF99=1
else
    PLATFORM_DVF99=0
fi

USER_ID=$(id -u 2>/dev/null)

if [ "$?" == "0" ] && [ "$USER_ID" == "0" ]; then
    ROOT_ACCESS=1
else
    ROOT_ACCESS=0
fi

if [ $PLATFORM_DVF99 -eq 0 ]; then
    AVAYA_PATH_APPLICATION="/AvayaDir/SIP/application"
    AVAYA_PATH_APP_RWDATA="${AVAYA_PATH_APPLICATION}"
    AVAYA_PATH_APP_LOG_FILES="${AVAYA_PATH_APP_RWDATA}/LogFiles"
    AVAYA_PATH_SYS_LOG_FILES="/var/log"
    AVAYA_PATH_DHCP_LEASES="/var/lib/dhclient"
    AVAYA_PATH_DHCP="/var/run/dhcp"
    AVAYA_PATH_DHCP_TMP="/tmp"
    AVAYA_PATH_TMP="/tmp"
    AVAYA_PATH_SYS_LOG_ACTIVE="${AVAYA_PATH_TMP}/logs"
    AVAYA_PATH_CORE_DUMPS="/data/crash"
    BITS_PER_PIXEL=32
else
    AVAYA_PATH_APPLICATION="/AvayaDir/application"
    source /AvayaStatic/etc/avaya_paths
    BITS_PER_PIXEL=24
fi

#timings for sar
end_time=$(date +%H:%M:%S)
start_time=$(awk 'BEGIN { print strftime("%H:%M:%S",systime()-60*60); exit }')

audio_report_file=${AVAYA_PATH_TMP}/Audio_Report.tar.gz
memory_zip_filename=memory_exhausted.tgz
scr_file=$(awk 'BEGIN{FS="[xp:]"} {print "screenshot_"$2"_"$3"_"}' /sys/class/graphics/fb0/modes)${BITS_PER_PIXEL}.raw

zip_file_base=phone_report

if [ "$ROOT_ACCESS" == "1" ]; then
    zip_file=${zip_file_base}.tar.gz
else
    zip_file=${zip_file_base}_${USER}.tar.gz
fi

sds_files="${AVAYA_PATH_SYS_LOG_ACTIVE}/avaya_phone.log"
sds_files="$sds_files ${AVAYA_PATH_SYS_LOG_ACTIVE}/bluetoothd_logs.txt"
sds_files="$sds_files ${AVAYA_PATH_SYS_LOG_ACTIVE}/hfpag_log.txt"
sds_files="$sds_files ${AVAYA_PATH_TMP}/remainingLoginAttempt.txt"
sds_files="$sds_files /run/lighttpd_webgui.conf"
sds_files="$sds_files ${AVAYA_PATH_APP_RWDATA}/ConfigStatus_Web_*.xml"
sds_files="$sds_files ${AVAYA_PATH_TMP}/logs/cgi_log.log"

if [ -e "${AVAYA_PATH_TMP}/sid.txt" ]; then
    sds_files="$sds_files ${AVAYA_PATH_TMP}/sid.txt"
else
    echo "Session file for Web UI does not exist"
fi

if [ $PLATFORM_DVF99 -eq 0 ]; then
    sds_files="$sds_files ${AVAYA_PATH_SYS_LOG_ACTIVE}/oldlogsdontouch"
    sds_files="$sds_files ${AVAYA_PATH_APP_RWDATA}/*.txt"
else
    sds_files="$sds_files ${AVAYA_PATH_SYS_LOG_STAGING}"
    sds_files="$sds_files ${AVAYA_PATH_DUMP_STAGING}"
    # css logs
    sds_files="$sds_files ${AVAYA_PATH_SYS_LOG_ACTIVE}/css_log.log"
    sds_files="$sds_files ${AVAYA_PATH_SYS_LOG_ACTIVE}/css_log_staging"
    # dbus-monitor logs
    sds_files="$sds_files ${AVAYA_PATH_SYS_LOG_ACTIVE}/dbusmon.log"
    sds_files="$sds_files ${AVAYA_PATH_DBUSMON_STAGING}"
    # hcidump logs
    sds_files="$sds_files ${AVAYA_PATH_SYS_LOG_ACTIVE}/hcidump.log"
    sds_files="$sds_files ${AVAYA_PATH_HCIDUMP_STAGING}"
fi

#sds_files="$sds_files ${AVAYA_PATH_APP_LOG_FILES}/EndpointLog.txt"
sds_files="$sds_files ${AVAYA_PATH_APP_LOG_FILES}/EndpointLog*.txt"

sds_files_small=$sds_files

if [ -r "$audio_report_file" ] ; then
    sds_files="$sds_files $audio_report_file"
fi

crash_report_files=$sds_files
crash_report_files="$crash_report_files ${AVAYA_PATH_TMP}/REPORT.txt"
crash_report_files="$crash_report_files ${AVAYA_PATH_TMP}/${scr_file}"
crash_report_files="$crash_report_files ${AVAYA_PATH_SYS_LOG_FILES}/css-ramdump.tar.gz"

sds_files="$sds_files ${AVAYA_PATH_SYS_LOG_FILES}/*"

report_generate_screenshot()
{
    cat /dev/fb0 > ${AVAYA_PATH_TMP}/${scr_file}
    touch ${AVAYA_PATH_TMP}/${scr_file}
}

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
    if [ $PLATFORM_DVF99 -eq 0 ]; then
        cat  ${AVAYA_PATH_TMP}/last_reset_cause.txt >> $report_file
    else
        cat  ${AVAYA_PATH_SYS_LOG_FILES}/last_reset_cause.txt >> $report_file
    fi
    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'
    if [ $PLATFORM_DVF99 -eq 0 ]; then
        run_command 'Heartbeat status' 'cat /tmp/heartbeat.txt'
        run_command 'Platform Configuration' 'cat /nvdata/platform.cfg'
    else
        run_command 'Platform Configuration' 'swversion.sh'
        if [ -x ${AVAYA_PATH_BIN}/css_get_dump.sh ]; then
            # The command will also generate CSS ramdump in case if CSS state is panic
            run_command 'CSS status' "${AVAYA_PATH_BIN}/css_get_dump.sh"
        fi
        run_command 'BT Process status' 'ps -eLo uid,pid,tid,cmd'
    fi
    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 ${AVAYA_PATH_CORE_DUMPS}/"
    run_command 'Application directory' "ls -al ${AVAYA_PATH_APP_RODATA}/"
    run_command 'Product ID' "configshow read CC_UNIT"
    run_command 'Default Server Mode' "configshow read DEFAULT_SERVER_MODE"
    run_command 'DES Support' "configshow read CONFIGDATA_DES_SUPPORT"
    display_reset_cause
    ls ${AVAYA_PATH_SYS_LOG_ACTIVE}
    if [ "$ROOT_ACCESS" == "1" ]; then
        if [ -f ${AVAYA_PATH_SYS_LOG_ACTIVE}/96x1_dump ]; then
            rm ${AVAYA_PATH_SYS_LOG_ACTIVE}/96x1_dump
        fi
        # Uncomment when application creates a handler for SIGINT
        # kill -2 $(ps x | grep "$app_dir/96" | grep -v gre | awk '{print $1}')
        if [ ! -r "${AVAYA_PATH_SYS_LOG_ACTIVE}/96x1_dump" ]; then
            touch ${AVAYA_PATH_SYS_LOG_ACTIVE}/96x1_dump
        fi
    fi
}

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()
{
    if [ $PLATFORM_DVF99 -eq 0 ]; then
        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'
    fi
}

memory_command()
{
    category=Memory
    cat ${AVAYA_PATH_TMP}/tmp_usage | awk '{print "Used:",$1,"Bytes"}' > ${AVAYA_PATH_TMP}/tmp_usageh
    run_command 'TMP Folder Memory Information' "cat ${AVAYA_PATH_TMP}/tmp_usageh"
    run_command 'TMP Files List' "ls -laR ${AVAYA_PATH_TMP}"
    rm ${AVAYA_PATH_TMP}/tmp_usageh
}

threads_command()
{
    category=Threads
    binary_num=$(ls ${AVAYA_PATH_APPLICATION}/*.bin | wc -l)
    if [ $binary_num -eq 1 ]; then
        app_filename=$(basename $(ls ${AVAYA_PATH_APPLICATION}/*.bin))
        pid_of_app=$(ps ax | grep "$app_filename" | grep -v grep | 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
}

knllog()
{
    echo "Dumping knllog to /tmp/knllog.txt"
    echo 1 > /proc/sys/knllog/enable
    echo 500000 > /proc/sys/knllog/entries
    echo 0x1f > /proc/sys/knllog/irq_sched_enable
    echo 1 > /proc/sys/knllog/clear; sleep 3; echo 1 > /proc/sys/knllog/dump
    echo 0 > /proc/sys/knllog/entries
    echo "Finished......Bye"
}

help()
{
    echo "$0 - Utility to prepare and output phone system information"
    echo "Options:"
    echo "-l <BYTES> - Limit report file size"
    if [ "$ROOT_ACCESS" == "1" ]; then
        echo "-k - interupt log of last 3 seconds"
    fi
    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 [ $memory_flag -eq 1 ]; then
        echo "Module : Memory 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
    memory_flag=0
    threads_flag=1
    crash=0
    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 [ "$memory_flag" == "1" ]; then
        echo "Generating report for Memory information"
        memory_command
    fi
    if [ "$threads_flag" == "1" ]; then
        echo "Generating report for Threads information"
        threads_command
    fi
    echo "All reports have been generated"
}

zip_files()
{
    echo "Generating Avaya Phone report archive"
    date=$(date +%k%M%d%m%g|sed 's/ //')
    run_commands_by_flags
    mv $report_file ${AVAYA_PATH_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 ${AVAYA_PATH_TMP}/REPORT.txt ${AVAYA_PATH_SYS_LOG_ACTIVE}/96x1_dump ${AVAYA_PATH_SYS_LOG_ACTIVE}/avaya_phone.log ${AVAYA_PATH_SYS_LOG_ACTIVE}/bluetoothd_logs.txt ${AVAYA_PATH_SYS_LOG_ACTIVE}/hfpag_log.txt ${AVAYA_PATH_TMP}/knllog.txt
        rm -rf ${AVAYA_PATH_TMP}/REPORT.txt ${AVAYA_PATH_TMP}/report_* ${AVAYA_PATH_TMP}/tmp.* ${AVAYA_PATH_TMP}/knllog.txt
        echo "Done."
        exit 0
    fi
   
    rm -rf ${AVAYA_PATH_TMP}/$zip_file
    temp_file=$(mktemp -t)

    if [ "$ROOT_ACCESS" == "1" ]; then
        find_perm=
    else
        # On Broadcom phones craft group is rarely used. To allow access to files for craft user, 
        # read access for other users is enabled (permissions for new files are 644 by default). 
        # On Sonic phones default file permissions are 640, so craft group is used to allow access for craft user.
        if [ $PLATFORM_DVF99 -eq 0 ]; then
            find_perm="-perm -0004"
        else
            find_perm="-perm -0040 -group $USER_ID"
        fi
    fi
    
    
    if [ "${memory_flag}" -eq "1" ]; then
        zip_file=$memory_zip_filename
    fi

    # backup the existing phone report archive if it exists before creating new one to save disk space
    if [ "$ROOT_ACCESS" == "1" ]; then
        phone_report_location=${AVAYA_PATH_SYS_LOG_FILES}
        mkdir -p $phone_report_location

        if [ -f $phone_report_location/$zip_file ]; then
            mv $phone_report_location/$zip_file $phone_report_location/$zip_file.bak
        fi
    fi

    # do not add 'phone_report*' and 'memory_exhausted*' files into new phone report archive
    file_list=$(find $sds_files $find_perm -type f ! -name $zip_file_base* ! -name $memory_zip_filename* 2>/dev/null)

    if [ -r "${AVAYA_PATH_APP_RWDATA}/config.xml" ] ; then
        # When these files are in the original location, the find command on line 368 fails because of permissions. These files have to be included individually in the list.
        file_list="$file_list ${AVAYA_PATH_APP_RWDATA}/config.xml"
    fi

    if [ -r "${AVAYA_PATH_APP_RWDATA}/configcache.xml" ] ; then
        # When these files are in the original location, the find command on line 368 fails because of permissions. These files have to be included individually in the list.
        file_list="$file_list ${AVAYA_PATH_APP_RWDATA}/configcache.xml"
    fi

	if [ -r ${AVAYA_PATH_APP_RWDATA}/BTCache.xml ]; then
		file_list="$file_list ${AVAYA_PATH_APP_RWDATA}/BTCache.xml"
	fi
    echo tar -C ${AVAYA_PATH_TMP} -zcvf $temp_file $file_list REPORT.txt
    if ! tar -C ${AVAYA_PATH_TMP} -zcvf $temp_file $file_list REPORT.txt ; then
        echo "Error: Failed to prepare ${AVAYA_PATH_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 $find_perm -type f 2>/dev/null)

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

        rm -rf $temp_file

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

    mv $temp_file ${AVAYA_PATH_TMP}/$zip_file
    rm -rf ${AVAYA_PATH_TMP}/REPORT.txt ${AVAYA_PATH_TMP}/SAR_ALL_REPORT.txt

    echo "Avaya Phone report archive have been generated"
    if [ "$ROOT_ACCESS" == "1" ]; then
        mv ${AVAYA_PATH_TMP}/$zip_file $phone_report_location/$zip_file
        chown root:craft $phone_report_location/$zip_file
        chmod 640 $phone_report_location/$zip_file
    else
        phone_report_location=${AVAYA_PATH_TMP}
    fi

    echo "Archive name on Avaya Phone : $phone_report_location/$zip_file"
}

crash_report()
{
    run_commands_by_flags
    mv $report_file ${AVAYA_PATH_TMP}/REPORT.txt
    report_generate_screenshot

    temp_file=$(mktemp -t)
    # find validates file list so that tar won't fail
    file_list=$(find $crash_report_files -type f 2>/dev/null)
    echo executing tar -C ${AVAYA_PATH_TMP} -zcvf $temp_file $file_list
    if ! tar -C ${AVAYA_PATH_TMP} -zcvf $temp_file $file_list >/dev/null 2>&1; then
        echo "Error: Failed to prepare ${AVAYA_PATH_TMP}/$zip_file archive"
        exit 1
    fi

    crash_filename=${AVAYA_PATH_SYS_LOG_FILES}/wd_crash.tgz
    mv $temp_file $crash_filename
    logrotate -f /etc/logrotate.conf
    echo "Crash report has been generated. File: $crash_filename"
}

args=`getopt -o hakmcl:  -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
            ;;
        -k)
            if [ "$ROOT_ACCESS" == "1" ]; then
                knllog
            else
                echo "knllog: allowed only for root"
            fi
            exit 1
            ;;
        -m)
            if [ "$ROOT_ACCESS" == "1" ]; then
                memory_flag=1
            else
                echo "Memory category allowed only for root"
            fi
            shift
            ;;
        -l)
            total_size=$2
            shift 2
            ;;
        -c)
            if [ "$ROOT_ACCESS" == "1" ]; then
                crash=1
            else
                echo "Crash report is allowed only for root, '-c' parameter is ignored"
            fi
            shift
            ;;
        --)
            break
            ;;
        *  )
            echo "No such option: $1"
            help
            exit 1
            ;;
    esac
done

if [ "${memory_flag}" -eq "1" ]; then
    logrotate -f /etc/logrotate.conf
fi

echo "phone-report in progress"

if [ "${crash}" -ne "1" ]; then 
    # regular zipped report
    zip_files
else
    crash_report
fi

if [ "$ROOT_ACCESS" == "1" ] && [ -f ${AVAYA_PATH_SYS_LOG_ACTIVE}/96x1_dump ]; then
    rm ${AVAYA_PATH_SYS_LOG_ACTIVE}/96x1_dump
fi

