shell-base/module.lib

128 lines
2.9 KiB
Bash

#!/bin/bash
module_confirm () {
local FILE
local DIR
local NAME
DIR=$1
NAME=$2
# echo finding $NAME in $DIR
FILE="$(find ${DIR} -type f -name "${NAME}.mod" -o -name "${NAME}".sh)"
# echo files found $FILE
COUNT=0
if [ "$FILE" ]; then
COUNT=$(echo $FILE | xargs -n 1 | wc -l)
fi
# echo Number: $COUNT
if [ $COUNT -gt 1 ]; then
echo two or more modules of same name found, aborting
echo $FILE | xargs -n 1
return 1
fi
[ $COUNT == 1 ] && echo $FILE && return 0
return 1
}
# if succesfull returns the path
function module_find () {
[ ! $1 ] && echo "no module specified" && return 1
local MDIRS
local MDIR
local DIRS
local MODULE=$1
# Precidence is user. current hosts, all hosts, current network, all networks, base
DIRS=( \
$([ $BASH_SHELL_USER ] && echo $HOME/$BASH_SHELL_USER || echo $HOME/bash/shell) \
$BASH_SHELL_HOST/$(hostname)
$BASH_SHELL_HOST/all \
$BASH_SHELL_NETWORK/$NETWORKNAME \
$BASH_SHELL_NETWORK/all \
$BASH_SHELL_BASE \
)
# echo ${DIRS[@]}
MDIRS=()
j=0
cnt=${#DIRS[@]}
for ((i=0;i<cnt;i++)); do
DIR="${DIRS[i]}/modules"
[ -d $DIR ] && MDIRS[j]=$DIR && j+=1
done
[ $MODULE_DIRS ] && MDIRS=("$MODULE_DIRS" "${MDIRS[@]}")
# echo Module Directories ${MDIRS[@]}
for MDIR in "${MDIRS[@]}"
do
# echo mdir $MDIR name $MODULE
RES=$(module_confirm "$MDIR" "$MODULE")
[ $? -eq 0 ] && echo $RES && return 0
done
return 1
}
module_load () {
[ ! $1 ] && echo "no module specified" && return 1
# (return 0 2>/dev/null) && echo "module_load was sourced" || echo "module_log was executed"
local FILE
FILE=$(module_find $1)
[ $? -ne 0 ] && echo no module $1 found && return 1
# source $FILE "$0"
[[ $BASHPID -eq $$ ]] || echo $FILE
source $FILE
return 0
}
module_loaded () {
[ ! $1 ] && echo "no module specified" && return 1
local func
local ret
local file
ret=0
# function_list | grep module
file=$(module_find $1)
[ ! $file ] && echo no module $1 found && return 1
# echo "$(function_list $file)"
for func in $(function_list $file)
do
[ ! $(function_list | grep $func) ] && ret=1
[[ $2 = -vv ]] && ([[ $ret = 0 ]] && echo "$func loaded" || echo "$func not loaded")
done
[[ $2 = -v ]] && echo "module: $1" && ([[ $ret = 0 ]] && echo "all functions " || echo "some or all functions not loaded")
[[ $ret = 0 ]] && echo "loaded"
return $ret
}
# exported for login environment
export -f module_load
export -f module_find
export -f module_confirm
function test_modules {
RED='\033[0;31m'
NC='\033[0m' # No Color
echo module to test: $1
echo --------------------
echo -e "testing: ${RED}module_find${NC}"
FILE=$(module_find $1)
[ $? -ne 0 ] && echo no module $1 found && return 1
echo module $FILE found
# . $FILE
echo ---------------
echo -e "testing: ${RED}module_load${NC}"
module_load $1
[ $? -ne 0 ] && echo no module $1 found && return 1
echo loaded module $1
echo ----------------------
echo -e "testing: ${RED}module_loaded${NC}"
module_loaded $1
}
#comment this out if testing
unset -f test_modules