#! /bin/bash
# Copyright 2019, Cumulus Networks, Inc.  All rights reserved.
#
# Record dot1x command state for cl-support
#
#TIMEOUT=180
#DEFAULT

module=${0##*/}

funcs=(config)

func_config()
{
    filename="/etc/hostapd.conf"
    interfaces=""

    # Check if the file exists
    if [ ! -f "$filename" ]; then
        return 0
    fi

    # Check hostapd the process is running
    if ! pgrep hostapd > /dev/null; then
        return 0
    fi

    match=$(grep '^interfaces=' "$filename")
    if [ -n "$match" ]; then
        interfaces=$(echo "$match" | awk -F '=' '{print $2}')
    fi

    if [ ! -z "$interfaces" -a "$interfaces" != " " ]; then
        if_list=$(echo "$interfaces" | tr ',' ' ')
        for iface in $if_list; do
            exec_cmd dot1x.mibs hostapd_cli -i $iface mib
            exec_cmd dot1x.interfaces hostapd_cli -i $iface all_sta
        done
        wait
    fi
}

# 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

    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
