#!/bin/bash

_link_editor() {
    COMPREPLY=()
    CURR="${COMP_WORDS[COMP_CWORD]}"
    PREV="${COMP_WORDS[COMP_CWORD-1]}"
    PREPREV="${COMP_WORDS[COMP_CWORD-2]}"
    if [[ ${COMP_CWORD} -eq 1 ]] ; then
        COMPREPLY=( $(compgen -W "-d -l --help --version" -- ${CURR}) )
        return 0
    fi

    if [[ "${PREPREV}" == "-l" ]] ; then
        COMPREPLY=( $(compgen -W "-t -f -r" -- ${CURR}) )
        return 0
    elif [[ "${PREPREV}" == "-d" ]] ; then
        COMPREPLY=( $(compgen -W "-f -r" -- ${CURR}) )
        return 0
    fi

    if [[ "${PREV}" == "-t" || "${PREV}" == "-p" ]] ; then
        if [[ "${COMP_WORDS[1]}" == "-l" ]]; then
            LINK="${COMP_WORDS[2]}"
            if [[ "$LINK" != "" && -L "$LINK" ]] ; then
                if [[ "${CURR}" == "" ]]; then
                    RLINK="$(readlink "$LINK")"
                    COMPREPLY=( "\"${RLINK}\"" )
                    return 0
                fi
            fi
        fi
    fi

    if [[ "${PREPREV}" == "-t" || "${PREPREV}" == "-p" ]] ; then
        COMPREPLY=( "-y" "--yes" )
        return 0
    fi

    if [[ "${COMP_WORDS[1]}" == "-l" && "$COMP_CWORD" -eq 5 ]]; then
        if [[ "${PREPREV}" == "-f" ]] ; then
            COMPREPLY=( $(compgen -W "-r" -- ${CURR}) ) 
            return 0
        elif [[ "${PREPREV}" == "-r" ]] ; then
            COMPREPLY=( $(compgen -W "-f" -- ${CURR}) ) 
            return 0
        fi
    fi
    if [[ "${COMP_WORDS[1]}" == "-d" && "$COMP_CWORD" -eq 7 ]]; then
        COMPREPLY=( $(compgen -W "-R" -- ${CURR}) ) 
        return 0
    fi
}

complete -o default -F _link_editor link-editor
complete -o default -F _link_editor ./link-editor
complete -o default -F _link_editor ./build/link-editor
