#!/bin/bash
SOURCE="$0"
source /usr/lib/elive-tools/functions
#EL_REPORTS="1"
#el_make_environment

main(){
    # pre {{{
    local filename match matches

    filename="$1"
    shift
    # }}}

    # Usage
    if [[ -z "${filename}" ]] ; then
        echo -e "This tool searches a file from your actual directory recursively, if found only one match it directly edits it with your EDITOR variable, otherwise it will return an error showing you the possible matches"
        echo -e "Usage: $(basename $BASH_SOURCE) filename"
        exit 1
    fi

    if [[ -z "$EDITOR" ]] ; then
        el_warning "EDITOR variable is not set, assign it to your .bashrc / .zshrc"
        if [[ -x "/usr/bin/vim" ]] ; then
            el_warning "we will fallback to vim"
            EDITOR="vim"
        else
            el_warning "we will fallback to nano"
            EDITOR=nano
        fi
    fi

    matches="$( find . -type f -iname '*'$filename'*' \( -not -path '*'.git'*' -not -path '*'.svn'*' \) )"

    if [[ -z "$matches" ]] ; then
        NOREPORTS=1 el_error "no matches found, maybe it's a symlink?"
        exit 1
    fi

    if [[ "$( echo "$matches" | wc -l )" -eq 1 ]] ; then
        echo "Found:"
        echo "$matches" | grep --color=auto "$filename"
        echo ""
        #el_explain 0 "going to run __${EDITOR}__, press __Enter__ to continue"
        #read nothing

        $EDITOR "$matches"
    fi

    if [[ "$( echo "$matches" | wc -l )" -gt 1 ]] ; then
        echo -e "\nMultiple matches found:"
        echo "$matches" | grep --color=auto "$filename"

        $EDITOR $matches
    fi

}

#
#  MAIN
#
main "$@"

# vim: set foldmethod=marker :
