#! /bin/bash
# Copyright (C) 2018-2021 Cumulus Networks, Inc.  All rights reserved.
#
# Record nvue command state for cl-support
#
#TIMEOUT=90
#DEFAULT

HOME_DIR=false
LOG_MARKER="####"

set_temp_home() # Reference: RM #3141793
{
    if [[ ! -v HOME ]]; then
        echo "$LOG_MARKER HOME environment variable is not set"
        HOME_DIR=$(mktemp -d -t nvue-temp-home-XXXXXXX)
        echo "$LOG_MARKER Creating temporary HOME directory: '$HOME_DIR'"
        export HOME=$HOME_DIR
    fi
}

unset_temp_home() # Reference: RM #3141793
{
    if [ "$HOME_DIR" != false ]; then
	echo "$LOG_MARKER Deleting temporary HOME directory: '$HOME_DIR'"
        rm -rf $HOME_DIR
    fi
}

# Also capture environment variables of the shell
# that invoked the cl-support. For debugging purposes.
# Reference: RM #3141793
log_env_params()
{
    echo "$LOG_MARKER Capturing current environment variables"
    env | sed -e "s/^/$LOG_MARKER >> /g"
}

module=${0##*/}

funcs=(config)

func_config()
{
    exec_cmd nvue.config nv config diff empty applied
    cp -a --parents /var/lib/nvue $SUP_TOPDIR
}

# 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 ;;
    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

    log_env_params

    for func in ${funcs[@]}; do
        [ $SUP_VERBOSE -eq 1 ] && echo "$module.$func" 1>&2
        date +"### $module.$func Started at %F-%T.%N"
        set_temp_home # Reference: RM #3141793
        { time func_$func 2>&$stderr  ; } 2>$tfile
        read secs < $tfile
        unset_temp_home # Reference: RM #3141793
        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
