1 contributor
#!/bin/bash
test -n "$1" \
&& egrep -q '^[[:digit:]]+$' <<< $1 \
&& DEFAULT_ENTRY="$1"
# mettre une valeur quelconconque pour entrer en mode deboggage, vide pour prod
DEBUG=
unset menuadm
declare -A menuadm
function build_menu () {
awk -F'::' -v dq='"' \
'BEGIN {
printf("unset action label translation;\n")
printf("declare -a label translation action;\n")
}
!/^\s*(#|$)/ {
if ($2 != "") {
printf("translation[${#translation[*]}]=${#label[*]};\n")
}
printf("action[${#action[*]}]=%s;\n", dq $2 dq)
printf("label[${#label[*]}]=%s;\n", dq $1 dq)
}' ${menuadm[menulist]}
}
function show_menu_debug () {
build_menu
eval $(build_menu)
read
until check_answer; do
show_labels
read -p "Choix: "
done
echo "${action[$REPLY]}"
}
function show_menu () {
eval $(build_menu)
until check_answer; do
show_labels
test -n "$DEFAULT_ENTRY" \
&& test $DEFAULT_ENTRY -ge 0 \
&& test $DEFAULT_ENTRY -lt ${#translation[*]} \
&& DEFAULT_ENTRY_LABEL="$(get_chapter)"
read -p "Choix${DEFAULT_ENTRY_LABEL}: "
test -n "$DEFAULT_ENTRY_LABEL" \
&& REPLY=${REPLY:-$DEFAULT_ENTRY}
done
eval "${action[$REPLY]}"
}
function get_chapter () {
for ((i=0, j=0; i<${#label[*]}; i++)); do
if test -z "${action[$i]}"; then
test -n "$DEFAULT_ENTRY" && test $DEFAULT_ENTRY -ge $j && chapter=${label[i]}
else
let j++
fi
done
echo -e " [$chapter / ${label[${translation[$DEFAULT_ENTRY]}]}]"
}
function show_labels () {
for ((i=0, j=0; i<${#label[*]}; i++)); do
if test -z "${action[$i]}"; then
prefix="\n : "
else
prefix="$j:-->"
let j++
fi
echo -e "$prefix:${label[$i]}"
done | column -ets ":"
}
function check_answer () {
test -n "$REPLY" \
&& egrep -q '^[[:digit:]]+$' <<< $REPLY \
&& test $REPLY -ge 0 \
&& test $REPLY -lt ${#translation[*]} \
&& REPLY=${translation[$REPLY]}
}
# répertoire éléments du menu, priorité au menu perso
if test -d $HOME/.local/share/$(basename $0); then
menuadm[share]=$HOME/.local/share/$(basename $0)
else
menuadm[share]=/usr/local/share/$(basename $0)
fi
menuadm[keys]="${menuadm[share]}/keys"
menuadm[contents]="${menuadm[share]}/contents"
menuadm[api]=${menuadm[share]}/api
# récupération de la config
for conf in /etc/$(basename $0)/$(basename $0).conf $HOME/.config/$(basename $0)/$(basename $0).conf; do
if test -r $conf; then
eval $(awk -F'=' '!/^\s*(#|$)/ {
printf("menuadm[%s]=%s\n",
gensub("^\\s*(\\w.*\\w)\\s*$","\\1","",$1),
gensub("^\\s*(\\w.*\\w)\\s*$","\\1","",$2))
}' $conf)
fi
done
test -r ${menuadm[api]} && source ${menuadm[api]}
# si pas de menu à afficher, on quitte...
test -d ${menuadm[contents]} || exit 1
for menu in ${menuadm[contents]}/*; do
if test -r $menu; then
menuadm[menulist]+=$menu
menuadm[menulist]+=" "
fi
done
if test -n "$DEBUG"; then
show_menu_debug
else
show_menu
fi