#!/bin/bash
# Copyright (c) 2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this material, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this material and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES
# SPDX-License-Identifier: LicenseRef-NvidiaProprietary#
# Record synced state; used by cl-support
#

#TIMEOUT=90
#DEFAULT

module=${0##*/}
json=
jexec=
funcs=(synced)
SYNCECTL=/usr/bin/syncectl

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) ;;
	l) echo ${funcs[@]}
	   exit 0 ;;
	*) ;;
    esac
done
shift $((OPTIND - 1))

func_synced()
{
    # if synced.service is not running: exit
    if systemctl -q is-active synced.service; then
        [ $SUP_VERBOSE -eq 1 ] && echo "syncectl show status" 1>&2
        exec_cmd syncectl.status $SYNCECTL show status

        [ $SUP_VERBOSE -eq 1 ] && echo "syncectl show interface status" 1>&2
        exec_cmd syncectl.intf.status $SYNCECTL show interface status

        [ $SUP_VERBOSE -eq 1 ] && echo "syncectl show interface counters" 1>&2
        exec_cmd syncectl.intf.counters $SYNCECTL show interface counters
    fi
}

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
