#!/bin/bash
# Copyright (C) 2020-2021 NVIDIA Corporation. ALL RIGHTS RESERVED.
# Copyright 2017,2018,2019,2020 Cumulus Networks, Inc.  All rights reserved.
#
# Record CSMGR state for cl-support
#
# Note that cl-support expects the below three flags to be commented
#TIMEOUT=30
#DEFAULT
#ONCORE=csmgr

module=${0##*/}

funcs=(show)
jexec=
ifoutfmt=
jsonkey=

csmgr_show()
{
	# Capture crucial csmgr information that helps debug system level problems
	exec_cmd csmgr.show csmgrctl -s
	exec_cmd csmgr.show csmgrctl -s -j
	wait
}

# main
while getopts "c:jl" Option; do
    case $Option in
    c) [ $SUP_VERBOSE -eq 1 ] && # default submods
        echo ${module}: Invoked for "$OPTARG" core dumps 1>&2 ;;
    j) [ $SUP_VERBOSE -eq 1 ] && echo JSON output not yet implemented 1>&2
       jexec=-j json=--json ;;
    l) echo ${funcs[@]}
       exit 0 ;;
    *) ;;
    esac
done
shift $((OPTIND - 1))

main()
{
    local -r TIMEFORMAT='%2R seconds' tfile=/run/${module}_funcstime$$
    local secs
    if [ $# -ne 0 ]; then # only run specified sub-modules
       [ $SUP_VERBOSE -eq 1 ] && echo ${module}: run only submodules: $@ 1>&$stderr
       funcs=($@)
    fi

    for func in ${funcs[@]}; do
        [ $SUP_VERBOSE -eq 1 ] && echo "$module.$func" 1>&2
        date +"### $module.$func Started at %F-%T.%N"
        { time ${module}_$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
