#! /bin/bash
# Copyright 2017, Cumulus Networks, Inc.  All rights reserved.
#
# Collect platform hardware info and state, as well as basic
# system state (logs, systemd info, etc.); used by cl-support
#
# Note that cl-support expects the below three flags to be commented
#TIMEOUT=60
#DEFAULT
#ONCORE=all

module=${0##*/}

funcs=(coreinfo)
declare -a cores
gdb=

gdb_coreinfo()
{
    local cmd core full

    for cmd in ${cores[@]}; do
        full=$(type -p "$cmd")
        [ -z "$full" ] && {
            echo ${module}: Unable to find executable for "$cmd"
            continue ; }
        for core in ${SUP_TOPDIR}/core/${cmd}.*; do
            local cbase="${core##*/}"
            exec_cmd gdb."$cmd"_$cbase $gdb -q -n --batch \
                -ex 'set complaints 0' -ex 'set pagination off' \
                -ex 'set trace-commands on' -ex 'info proc' -ex t -ex bt \
                -ex 'info thread' -ex 'info frame' -ex 'info target' \
                -ex 'info shared' -ex 'info registers'  -ex 'info vector' \
                -e "$full" -c "$core"  
        done
    done
}

while getopts "c:jl" Option; do
    case $Option in
    c)  cores=${OPTARG//,/ }
        [ "$SUP_VERBOSE" -eq 1 ] &&
        echo ${module}: Invoked for "${cores[@]}" core dumps 1>&2 ;;
    j) ;;
    l) echo ${funcs[@]}
       exit 0 ;;
    *) ;;
    esac
done
shift $((OPTIND - 1))

main()
{
    local -r TIMEFORMAT='%2R seconds' tfile=/run/${module}_funcstime$$
    local secs
    PATH=$PATH:/usr/lib/frr:/opt/bin:/usr/local/bin:/usr/lib/dbus-1.0:/usr/lib/gnupg:/usr/lib/grub/i386-pc:/usr/lib/klibc/bin:/usr/lib/virt-what:/usr/lib/x86_64-linux-gnu/glib-2.0:/usr/share/mgmt-vrf/bin:/usr/lib64/mft/tcl/bin

    gdb=$(type -p gdb)
    [ -z "$gdb" ] && { echo ${module}: gdb package not installed ; return ; }

    for func in ${funcs[@]}; do
        [ $SUP_VERBOSE -eq 1 ] && echo "$module.$func" 1>&2
        date +"### $module.$func Started at %F-%T.%N"
        { time gdb_$func 2>&$stderr  ; } 2>$tfile
        read secs < $tfile
        echo "### $module.$func Completed in $secs"
    done
    rm $tfile
}

TIMEFORMAT="Module $module Completed in %2R seconds"
exec 42>&2
stderr=42

{ time main $@ 2>&$stderr ; } 2>&1

exit 0
