#!/bin/bash

# File Finder - filefinder
# Copyright 2012 Tony Brijeski <tb6517@yahoo.com>


DIALOGMENU="`which zenity` --width=400 --height=400"
DIALOG="`which zenity`"
TITLE="--title="
TEXT="--text="
EDITTEXT="--text-info --editable --filename="
FILESELECT="--file-selection"
MULTIFILESELECT="--file-selection --multiple"
DIRSELECT="--file-selection --directory"
ENTRY="--entry "
ENTRYTEXT="--entry-text "
MENU="--list --column=Pick --column=Info"
YESNO="--question "
MSGBOX="--info "
PASSWORD="--entry --hide-text "
TITLETEXT="File Finder"

if [ ! -f $HOME/.filefinderrc ]; then
    FILMGR=`$DIALOG $TITLE"$TITLETEXT" $TEXT"Please type in the name of the File Manager you wish to use to open the folder containing your search results." $ENTRY`
    if [ "$?" != "0" ]; then
        rm /tmp/filefinder.*
        exit 0
    fi
    cat > $HOME/.filefinderrc <<FOO
FILEMANAGER="$FILMGR"

FOO
    . $HOME/.filefinderrc
else
    . $HOME/.filefinderrc
fi

FLMGTEST=`which $FILEMANAGER`

if [ "$FLMGTEST" = "" ]; then
    rm $HOME/.filefinderrc
    $DIALOG TITLE"$TITLETEXT" $MSGBOX $TEXT"Your chosen File Manager does not exist. Exiting."
    exit 0
fi

while [ True ]; do

    FINDER=`$DIALOG $TITLE"$TITLETEXT" $TEXT"Please type in the name of the File or Folder to find." $ENTRY`
    if [ "$?" != "0" ]; then
        rm /tmp/filefinder.*
        exit 0
    fi

    if [ "$FINDER" = "QUIT" ]; then
        rm /tmp/filefinder.*
        exit 0
    fi
    
    find / -iname "*$FINDER*" | tee >($DIALOG $TITLE"$TITLETEXT" $TEXT"Searching for $FINDER. Please wait..." --progress --pulsate --auto-close) > /tmp/filefinder.tmp
    cat /tmp/filefinder.tmp
    if [ "`cat /tmp/filefinder.tmp | wc -l`" = "0" ]; then

        $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT"$FINDER not found."

    elif [ "`cat /tmp/filefinder.tmp | wc -l`" = "1" ]; then
        FOUND=`cat /tmp/filefinder.tmp`
        WHERE=`dirname "$FOUND"`
        $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT"$FINDER found in $WHERE.  Click OK to open folder."
        if [ "$?" = "0" ]; then
            $FILEMANAGER "$WHERE"
            rm /tmp/filefinder.*
            exit 0
        fi
    else
        rm /tmp/filefinder.menu
        cat /tmp/filefinder.tmp | while read LINE; do
            BASE=`basename "$LINE"`
            cat >> /tmp/filefinder.menu <<FOO
$LINE
$BASE 
FOO
        done

        SETCHOICE=`cat /tmp/filefinder.menu | $DIALOGMENU $TITLE"$TITLETEXT" $MENU $TEXT"Please choose which one you would like to open the folder for or cancel to exit." `
        if [ "$?" = "0" ]; then
            WHERE=`dirname "$SETCHOICE"`
            $FILEMANAGER "$WHERE"
            rm /tmp/filefinder.*
            exit 0
        fi
        
    fi
    

done
 

syntax highlighted by Code2HTML, v. 0.9.1