#!/bin/bash

_ipman_completions()
{
    local cur prev subcommands
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev1="${COMP_WORDS[COMP_CWORD-1]}"
    prev2="${COMP_WORDS[COMP_CWORD-2]}"
    prev3="${COMP_WORDS[COMP_CWORD-3]}"

    subcommands="status get-primary wait-for-init show set help"
    set_properties_bool="enable static-enable dhcp-enable linklocal-enable dhcp-linklocal-fallback"
    set_properties_text="static static-ip static-gateway config"
    net_types="static dhcp linklocal"

    if [[ ${COMP_CWORD} -eq 1 ]]; then
        COMPREPLY=( $(compgen -W "${subcommands}" -- ${cur}) )
        return 0
    fi

    if [[ ${COMP_CWORD} -eq 2 ]]; then
        case "${prev1}" in
            show|status|set)
                COMPREPLY=( $(compgen -W "$(netman list | tr '\n' ' ')" -- ${cur}) )
                return 0
                ;;
            *)
                COMPREPLY=()
                return 0
                ;;
        esac
    fi
    if [[ ${COMP_CWORD} -eq 3 ]]; then
        case "${prev2}" in
            status)
                COMPREPLY=( $(compgen -W "${net_types}" -- ${cur}) )
                return 0
                ;;
            set)
                COMPREPLY=( $(compgen -W "${set_properties_bool} ${set_properties_text}" -- ${cur}) )
                return 0
                ;;
            *)
                COMPREPLY=()
                return 0
                ;;
        esac
    fi

    if [[ ${COMP_CWORD} -eq 4 ]]; then
        echo ${set_properties_bool} | tr ' ' '\n' | grep -F -q -x "${prev1}"
        if [[ $? -eq 0 && "${prev3}" = "set" ]] ; then
            COMPREPLY=( $(compgen -W "0 1" -- ${cur}) )
        else
            COMPREPLY=()
        fi
        return 0
    fi

    return 0
}

complete -F _ipman_completions ipman