#!/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 ptp4l state; used by cl-support
#

#TIMEOUT=90
#DEFAULT

module=${0##*/}
json=
jexec=
funcs=(ptp4l)
PTP_DEBUG=/usr/lib/cumulus/ptpdebug
TSMON=/usr/lib/cumulus/tsmon

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_ptp4l()
{
    # if ptp4l.service is not running: exit
    if systemctl -q is-active ptp4l.service; then

	[ $SUP_VERBOSE -eq 1 ] && echo "ptpdebug show status" 1>&2
	exec_cmd ptp4l.status $PTP_DEBUG show status

	[ $SUP_VERBOSE -eq 1 ] && echo "ptpdebug show counters" 1>&2
	exec_cmd ptp4l.counters $PTP_DEBUG show counters

	[ $SUP_VERBOSE -eq 1 ] && echo "tsmon -m" 1>&2
	exec_cmd tsmon.m $TSMON -m

	[ $SUP_VERBOSE -eq 1 ] && echo "tsmon -n" 1>&2
	exec_cmd tsmon.n $TSMON -n

	[ $SUP_VERBOSE -eq 1 ] && echo "tsmon -p" 1>&2
	exec_cmd tsmon.p $TSMON -p

    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
