#!/usr/bin/env bash

# Copyright (C) 2008-2013 Bob Hepple
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

# http://bhepple.freeshell.org

set -eu

initialise() {
    local TEMP

    PROG=$(basename $0)
    VERSION="1.1"
    TYPE="f"
    ARGUMENTS="[pattern]"
    SHORT_DESC="Search for filenames in sub-directories."
    USAGE="Presently this is just a shorthand for:

find . -follow -type $TYPE -name '*pattern*' -print 2>/dev/null |sort"

    NEW_ARGS=( )

    ARGS="
ARGP_DELETE=quiet
ARGP_VERSION=$VERSION
ARGP_PROG=$PROG
##############################################################   
#OPTIONS:
#name=default sname arg       type range   description
##############################################################   
EXCLUDE=''    x     directory s    ''      exclude directory
DIR='f'       d     ''        b    'd'     search for a directory rather than a file
CD=''         C     directory s    ''      search from this directory rather than cwd
##############################################################   
ARGP_ARGS=[--] $ARGUMENTS
ARGP_SHORT=$SHORT_DESC
ARGP_USAGE=$USAGE"

    TYPE='f'

    exec 4>&1
    eval $(echo "$ARGS" | argp.sh "$@" 3>&1 1>&4 || echo exit $? )
    exec 4>&-

    TYPE="$DIR"
    [ "${EXCLUDE:-}" ] && EXCLUDE="-path \"${EXCLUDE:-}\" -prune -o ";
    [ "$CD" ] && {
        cd "$CD" || exit 1
    }

    NEW_ARGS=( "$@" )
    return 0
}

main() {
    for EXCLDIR in .svn nbproject .libs .deps 'CVS*'; do
        EXCLDIRS+="-path '*/$EXCLDIR' -prune -o "
    done

    EXPR="find . -follow $EXCLDIRS ${EXCLUDE:-} -type $TYPE -name '*$1*' -print 2>/dev/null |sort"
    [ $VERBOSE ] && echo $EXPR
    eval $EXPR
}

initialise "$@" && set -- "${NEW_ARGS[@]:-}"

main "$@"
