##################################
### Methods to be called by plugins
##################################

# list files in a directory consisting only of alphanumerics, hyphens and
# underscores
# $1 - directory to list
run_parts_list() {
    if [ $# -lt 1 ]; then
        echo "ERROR: Usage: run_parts_list <dir>" > /dev/stderr
        exit 1
    fi
    if [ ! -d "$1" ]; then
        echo "ERROR: Not a directory: $1" > /dev/stderr
        exit 1
    fi

    if [ -d "$1" ]; then
        for file in $(find -L $1 -mindepth 1 -maxdepth 1 -type f | sort -n) ; do
            basefile=$(basename $file)
            if [ -n "$(echo "$basefile" | egrep ^[0-9a-zA-Z_\-]*$)" ]; then
                echo $file
            fi
        done
    fi
}

# Load plugins.
#
# Params:
# $1 - mode (configure|run)
# needs variable PLUGIN_DIRS defined
load_plugins() {
    set -- "$@"
    MODE=$1
    debug "Loading plugins in MODE=$MODE:"
    FILENAMES=""
    NAMES=""
    for dir in $PLUGIN_DIRS ; do
        if [ -d "$dir" ]; then
            FILENAMES="$FILENAMES $(run_parts_list $dir)"
        fi
    done
    for file in $FILENAMES ; do
        NAMES="$NAMES $(basename $file)"
    done
    NAMES="$(echo $NAMES | tr "\t " "\n" | sort -u)"
    for name in $NAMES ; do
        for dir in $PLUGIN_DIRS ; do
            filename="$dir/$name"
            if [ -f "$filename" ]; then 
                debug "Loading plugin: $filename"
                . "$filename"
                break
            fi
        done
    done
}
