#! /bin/bash
# Copyright 2023 Cumulus Networks, Inc.  All rights reserved.
#
# Record asic-monitor state; used by cl-support
#

#TIMEOUT=135
#DEFAULT

module=${0##*/}
json=
jexec=
funcs=(dump)

func_dump()
{
    DEBUG_FILE=/tmp/asic_monitor_debug.log
    if [ -f $DEBUG_FILE ]; then
        rm $DEBUG_FILE
    fi

    asic_mon_pids=`systemctl show -P MainPID "asic-monitor*"`
    pid_list=$(echo $asic_mon_pids | tr " " "\n")
    asic_mon_pid=0
    # only one asic-monitor will be active at time.
    # pid list will have zero value for inactive asic-monitor instances
    # and non zero values for active asic-monitor service. Pick non-zero
    # value
    for pid in $pid_list
    do
        if [ $pid -ne 0 ]; then
            asic_mon_pid=$pid
        fi
    done

    echo $asic_mon_pid
    if [ $asic_mon_pid -ne 0 ]; then
        kill -SIGUSR2 $asic_mon_pid
        max_wait=5
        wait_sec=1
        while [ $wait_sec -le $max_wait ]
        do
            sleep 1
            if [ -f $DEBUG_FILE ]; then
                echo "ASIC Monitor debug log ready"
                break
            fi
            wait_sec=$((wait_sec + 1))
        done
        if [ -f $DEBUG_FILE ]; then
            cat $DEBUG_FILE > asic-monitor.dump
        fi
    else
        echo "ASIC Monitor is not Running" > asic-monitor.dump
    fi

    HFT_DATA_FILE=/var/run/cumulus/hft/hft_data.tar.gz
    HFT_CONFIG_STATUS_FILE=/var/run/cumulus/hft/hft_config.status
    HFT_DIR=/var/lib/cumulus/hft
    if [ -d $HFT_DIR ]; then
        if [ -f $HFT_DATA_FILE ]; then
            cp $HFT_DATA_FILE $HFT_DIR
        fi
        if [ -f $HFT_CONFIG_STATUS_FILE ]; then
            cp $HFT_CONFIG_STATUS_FILE $HFT_DIR
        fi
    else
        echo "$HFT_DIR dir is not present" >> asic-monitor.dump
    fi
}


while getopts "c:l" Option; do
    case $Option in
    c) ;;
    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 func_$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
