#!/bin/sh
# Copyright (C) 2010-2018 FARGOS Development, LLC
# Find a file by searching a set of directories; colon-separated
# paths are permitted.
# findFile fileName path [...]
# $Id$
# NOTE:  this shell script implementation has an alternate native implementation
initialPath=""
suffix=""
pathList=""
reportLimit=-1
sawSuffix=0
pathSep=':'

while test $# -gt 0
do
	case "${1}" in
	-h | -help | --help)
		printf "usage: %s [-1 | --all] [-s separator] fileOrDirName path [...]\n" "${0}" >&2
		printf "  path can contiguous elements, default separator is a colon\n" >&2
		printf "  -s separator = define alternate path separator character\n" >&2
		printf "  -1 = report first entry found only (-2 = report first two, etc.)\n" >&2
		printf "  --all = report all entries found (default)\n" >&2
		exit 1
		;;
	-[0-9]*)
		reportLimit=`expr 0 - ${1}` # convert negative to positive
		;;
	-all | --all)
		reportLimit=-1
		;;
	-s)	# allow path separator to be specified
		pathSep="${2}"
		shift
		;;
	*)
		if test ${sawSuffix} -eq 0
		then
			isAbsolute=`expr $1 : /` 
			if test ${isAbsolute} -eq 1
			then # output absolute filename as-is
				if test -e "${1}"
				then
					echo ${1}
					exit 0
				fi
			fi
			suffix=$1
			sawSuffix=1
		else
			arg=`echo $1 | sed -e 's/'${pathSep:-:}'/ /g'`
			pathList="${pathList}${pathList:+ }${arg}"
		fi
		;;
	esac
	shift
done

if test -z "${suffix}"
then
	printf "%s: no target file specified.\n" "${0}" >&2
	exit 1
fi
if test -z "${pathList}"
then
	printf "%s: no path elements specified.\n" "${0}" >&2
	exit 1
fi

foundCount=0
rc=1
for d in ${pathList}
do
	for f in ${d}/${suffix}
	do
		trueFile=`readlink -m ${f} 2>/dev/null`
		if test -z "${trueFile}"
		then # failed, probably due to busybox not supporting -m
			# fallback to -f
			trueFile=`readlink -f ${f}`
		fi
		if test -e ${trueFile}
		then # found file, output name
			echo ${f}
			rc=0
			foundCount=`expr ${foundCount} + 1`
			if test ${foundCount} -eq ${reportLimit}
			then # found maximum amount we want
				break
			fi
		fi
	done
	if test $foundCount -eq $reportLimit
	then # found maximum amount we want
		break
	fi
done
exit ${rc}
