#!/bin/bash
# Copyright (c) 2022, 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) 2022 NVIDIA CORPORATION & AFFILIATES
# SPDX-License-Identifier: LicenseRef-NvidiaProprietary#
# Record what-just-happened state; used by cl-support
#

#TIMEOUT=90
#DEFAULT

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

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

	[ $SUP_VERBOSE -eq 1 ] && echo "what-just-happened --export" 1>&2
	exec_cmd what-just-happened.pcap-export what-just-happened --export

	[ $SUP_VERBOSE -eq 1 ] && echo "docker exec what-just-happened supervisorctl status all" 1>&2
	exec_cmd what-just-happened.supervisorctl docker exec what-just-happened supervisorctl status all

	[ $SUP_VERBOSE -eq 1 ] && echo "what-just-happened dump" 1>&2
	exec_cmd what-just-happened.dump what-just-happened dump

	[ $SUP_VERBOSE -eq 1 ] && echo "docker logs what-just-happened" 1>&2
	exec_cmd what-just-happened.logs docker logs what-just-happened

    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
