f37b1d4ac1a8762d76fa958383e5748c9b579214
[packages/precise/mcollective.git] / ext / bash / mco_completion.sh
1 _mco() {
2   local agents options
3
4   COMPREPLY=()
5   local cur=${COMP_WORDS[COMP_CWORD]}
6   local prev=${COMP_WORDS[COMP_CWORD-1]}
7
8   # Where are the plugins?
9   local libdir=$(sed -n 's@libdir = @@p' /etc/mcollective/client.cfg)
10
11   # All arguments by options
12   noopt=($(tr ' ' '\n' <<<${COMP_WORDS[@]} | \
13     grep -v "^$cur$" | grep -v -- '^-'))
14
15   local count_noopt=${#noopt[@]}
16   local cmd=${noopt[0]}
17   local app=${noopt[1]}
18
19   # A bug in the output of --help prevents
20   # from parsing all options, so we list the common ones here
21   local common_options="-T --target -c --config --dt --discovery-timeout \
22     -t --timeout -q --quiet -v --verbose -h --help -W --with -F \
23     --wf --with-fact -C --wc --with-class -A --wa --with-agent -I \
24     --wi --with-identity"
25
26   if [ $COMP_CWORD -eq 1 ]; then
27     apps=$($cmd completion --list-applications)
28     COMPREPLY=($(compgen -W "$apps" -- "$cur"))
29   elif [ $COMP_CWORD -gt 1 ]; then
30     options="${common_options} $($cmd $app --help | grep -o -- '-[^, ]\+')"
31
32     if [ "x${app}" = "xrpc" ]; then
33       if [[ $count_noopt -eq 2 || "x${prev}" = "x--agent" ]]; then
34         # Complete with agents
35         agents=$($cmd completion --list-agents)
36         options="$options $agents"
37       elif [[ $count_noopt -eq 3 || "x${prev}" = "x--action" ]]; then
38         # Complete with agent actions
39         rpcagent=${noopt[2]}
40         actions=$($cmd completion --list-actions \
41                        --agent "$rpcagent")
42         options="$options $actions"
43       elif [ $count_noopt -gt 3 ]; then
44         # Complete with key=value
45         rpcagent=${noopt[2]}
46         rpcaction=${noopt[3]}
47         inputs=$($cmd completion --list-inputs \
48                       --agent "$rpcagent" --action "$rpcaction")
49         options="$options $inputs"
50       fi
51     fi
52
53     COMPREPLY=($(compgen -W "$options" -S ' ' -- "$cur"))
54   fi
55 }
56 [ -n "${have:-}" ] && complete -o nospace -F _mco mco
57