#!/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

########################
# Print help to stdout #
########################

usage() {
	echo "Usage: $PROG [directories] [-h] [-type f|d] [-newer file] [-maxdepth depth]

Recursive descent through the named directories (or CWD if none are
given) printing file names. Nothing like 'find' but possibly useful
where it doesn't exist." 

}

test_type() {
	[ -z "$TYPE" ] && return 0
	[ -$TYPE "$1" ] && return 0
	return 1
}

test_newer() {
	[ -z "$NEWER" ] && return 0
	[ "$1" -nt "$NEWER" ] && return 0
	return 1
}

find() {
    local ARG="$1"
	local PRE="$ARG"
	test_type "$ARG" && test_newer "$ARG" && echo "$ARG"
	[ "$ARG" = "/" ] && PRE=""
	DEPTH=`expr $DEPTH + 1`
    # don't follow symbollic links:
	if [ -d "$ARG" -a !  -h "$ARG" -a "$DEPTH" -le "$MAXDEPTH" ]; then
        for i in `ls $ARG`; do
			find "$PRE/$i"
		done
	fi
	DEPTH=`expr $DEPTH - 1`
}

##########################
#         M A I N        #
##########################

PROG=$(basename $0)
VERSION="1.1"
TYPE=""
NEWER=""
MAXDEPTH="1000"

# we're not using getopt because we're emulating the old 'find' options
# which are incompatible and excreble but set in stone
unset ARG
while [ "$1" ]; do
	A="$1"
	shift
	case "$A" in
		-h|-help|--help)
			usage
			exit 0
			;;
		-V)
			echo "$PROG: version $VERSION"
			exit 0
			;;
		-type)
			TYPE="$1"
			shift
			;;
		-newer)
			NEWER="$1"
			shift
			;;
		-maxdepth)
			MAXDEPTH="$1"
			shift
			;;
		*)
			if [ "$ARG" ]; then
				ARG="$ARG $A"
			else
				ARG="$A"
			fi
			;;
	esac
done

[ -z "$ARG" ] && ARG='.'

DEPTH=0
for i in "$ARG"; do
	find "$i"
done
