# serv(8) completion

# This completes on a list of all available services for the
# 'serv' command, followed by that script's available commands
#
_service_list()
{
    local serv_opts=()
    local i

    for ((i=1; i<COMP_CWORD; i++)); do
        [[ ${COMP_WORDS[i]} == "--user" ]] && serv_opts=(--user)
    done

    COMPREPLY=( $( serv "${serv_opts[@]}" list-all 2>/dev/null | awk 'NR>1 && !/unit files listed/ {print $1}' ; echo "list list-all list-startup" ) )
    COMPREPLY=( $( compgen -W '${COMPREPLY[@]}' -- "$cur" ) )
}

_service_usage_list()
{
    local service=
    local serv_opts=()
    local i

    for ((i=1; i<COMP_CWORD; i++)); do
        case ${COMP_WORDS[i]} in
            --user)
                serv_opts=(--user)
                ;;
            -*)
                ;;
            *)
                service=${COMP_WORDS[i]}
                break
                ;;
        esac
    done

    local USLIST=$(serv "${serv_opts[@]}" "${service##*/}" usage 2>/dev/null | sed -e "y/|/ /" -ne "s/^.*\(u\|U\|msg_u\)sage.*{\(.*\)}.*$/\2/p")
    COMPREPLY=( $( compgen -W '$USLIST' -- "$cur" ) )
}


_serv()
{
    local cur prev
    local i arg_count=0

    COMPREPLY=()
    _get_comp_words_by_ref cur prev

    # don't complete for things like killall, ssh and mysql if it's
    # the standalone command, rather than the init script
    [[ ${COMP_WORDS[0]} != "serv" ]] && return 0

    for ((i=1; i<COMP_CWORD; i++)); do
        [[ ${COMP_WORDS[i]} == -* ]] && continue
        ((arg_count++))
    done

    # don't complete past service and command tokens
    [ $arg_count -gt 1 ] && return 0

    if [[ $arg_count -eq 0 ]]; then
        _service_list
    else
        _service_usage_list
    fi

    return 0
} &&
complete -F _serv serv
