set -ue

shopt -s globstar nullglob

for module in ${MODULES[@]}; do
    . $LIB/pvl/$module.sh
done

. $LIB/pvl/util.sh
. $LIB/pvl/list.sh
. $LIB/pvl/cmd.sh

function main_help {
    cat <<END
Usage: $0 [options]

General:
    -h      display this help text
END
    
    for module in ${MODULES[@]}; do
        func_test ${module}_help && ${module}_help
    done
}

function main_opts {
    local module=

    # build opts string
    local opts=$(
        echo -n 'h'

        for module in ${MODULES[@]}; do
            module_getopts=${module}_GETOPTS
            echo -n ${!module_getopts:-}
        done
    )

    local OPTIND
    while getopts "$opts" opt; do
        local opt_module=

        if [ "$opt" = 'h' ]; then
            main_help
            exit 0;
        fi

        for module in ${MODULES[@]}; do
            if func_test ${module}_opt && ${module}_opt $opt "${OPTARG:-}"; then
                opt_module=$module
            fi
        done

        if [ "$opt_module" ]; then
            continue
        else
            die "opt: $opt"
        fi
    done
    shift $(($OPTIND - 1))
}

function main {
    local module=

    main_opts "$@"

    for module in ${MODULES[@]}; do
        func_test ${module}_init && ${module}_init
    done

    func_test ${MODULE_MAIN}_init && ${MODULE_MAIN}_init

    # initialize relative paths
    [ -z "$SRV" ] || cd $SRV

    ${MODULE_MAIN}_main
}
