# wl-paste(1) completion

_wl_clipboard_list_seats() {
    weston-info 2>/dev/null | sed -n '/wl_seat/{n;s/\s*name: //;p}'
}

_wl_clipboard_complete_types() {
    local cur prev types
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"
    types="$1"
    if [ "${cur:0:1}" = \' -o "${cur:0:1}" = \" ]; then
        COMPREPLY=($(compgen -W "$types" -- "$cur"))
    else
        COMPREPLY=($(compgen -W "$types" -- "$cur" | sed 's/;/\\;/g'))
    fi
}

_wl_clipboard_complete_paste_types() {
    local i cur primary seat cmd types
    for (( i = 0; i < "${#COMP_WORDS[@]}"; ++i )); do
        cur="${COMP_WORDS[i]}"
        case "$cur" in
            -p* | -[a-z]*p* | --primary)
                primary="yes"
                ;;
        esac
        case "$cur" in
            -s | -[a-z]*s | --seat)
                seat="${COMP_WORDS[i+1]}"
                ;;
            -s* | -[a-z]s*)
                seat=$(echo "$cur" | sed 's/-[^s]*s//')
                ;;
        esac
    done
    cmd="${COMP_WORDS[0]}"
    if [ -n "$primary" ]; then
        cmd="$cmd -p"
    fi
    if [ -n "$seat" ]; then
        cmd="$cmd -s $seat"
    fi
    cmd="$cmd -l"
    types="$($cmd 2>/dev/null)"
    _wl_clipboard_complete_types "$types"
}

_wl_paste_completion() {
    compopt +o default
    local cur prev opts types seats offset

    for (( offset=1; offset < COMP_CWORD; offset++ )); do
        cur="${COMP_WORDS[offset]}"
        if [ "$cur" = "-w" -o "$cur" = "--watch" ]; then
            _command_offset $(($offset+1))
            return
        fi
    done

    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"

    case "$cur" in
        ">"*)
            compopt -o default
            COMPREPLY=()
            return
            ;;
    esac

    case "$prev" in
        ">"*)
            compopt -o default
            COMPREPLY=()
            ;;
        -t | -[a-z]*t | --type)
            _wl_clipboard_complete_paste_types
            ;;
        -s | -[a-z]*s | --seat)
            seats="$(_wl_clipboard_list_seats)"
            COMPREPLY=($(compgen -W "$seats" -- "$cur"))
            ;;
        *)
            opts="-n --no-newline "
            opts+="-l --list-types "
            opts+="-p --primary "
            opts+="-w --watch "
            opts+="-t --type "
            opts+="-s --seat "
            opts+="-v --version "
            opts+="-h --help "
            COMPREPLY=($(compgen -W "$opts" -- "$cur"))
            ;;
    esac
}

complete -o default -F _wl_paste_completion wl-paste
