_enroot()
{
    local cmd= cur= prev= words=() cword=
    COMPREPLY=()

    _get_comp_words_by_ref -n : cur prev words cword

    if [ "${cword}" -eq 1 ]; then
        COMPREPLY+=($(compgen -W "batch bundle create exec export import list remove start version help" -- "${cur}"))
        return 0
    fi

    cmd="${words[1]}"

    case "${cmd}" in
    batch|bundle|create|exec|export|import|list|start|remove)
        if [ "${cword}" -gt 2 ] && printf "%s\n" "${words[@]:2:${cword}-2}" | grep -qv -- ^--; then
            # Stop doing completion after we got an argument, except for "remove" which takes vaargs.
            [ "${cmd}" != "remove" ] && return 0
        else
            # Show options completion if there are no double-dashes.
            if ! printf "%s\n" "${words[@]:2:${cword}-2}" | grep -qx -- --; then
                local opts=$(enroot "${cmd}" --help 2> /dev/null | grep -owE -- "--[[:alpha:]_-]+")
                COMPREPLY+=($(compgen -W "-- --help ${opts}" -- "${cur}"))
            fi
        fi
    esac

    case "${cmd}" in
    batch)
        COMPREPLY+=($(compgen -f -- "${cur}"))
        ;;
    bundle|create)
        COMPREPLY+=($(compgen -f -X "!(*.sfs|*.sqfs|*.sqsh|*.squashfs)" -- "${cur}"))
        COMPREPLY+=($(compgen -d -- "${cur}"))
        ;;
    export|remove)
        COMPREPLY+=($(compgen -W "$(enroot list 2> /dev/null)" -- "${cur}"))
        ;;
    import)
        compopt +o filenames
        [ "${#COMPREPLY[@]}" -eq 0 ] && compopt -o nospace
        [[ "${cur}" == *:// ]] && return 0
        COMPREPLY+=($(compgen -W "docker:// dockerd://" -- "${cur}"))
        __ltrim_colon_completions "${cur}"
        ;;
    start)
        COMPREPLY+=($(compgen -W "$(enroot list 2> /dev/null)" -- "${cur}"))
        COMPREPLY+=($(compgen -f -X "!(*.sfs|*.sqfs|*.sqsh|*.squashfs)" -- "${cur}"))
        COMPREPLY+=($(compgen -d -- "${cur}"))
        ;;
    esac
}

complete -F _enroot -o filenames -o nosort enroot
