#!/bin/bash -pe
# SPDX-License-Identifier: GPL-3.0-or-later
# Copyright 2024, Gerrit-John Los <los@lugons.org>

# for x in ffx fdx flx ;do ln fx "$x" ;done

shopt -s extglob

if [ "$1" = '-h' ] ;then
	cat 1>&2 <<-EOT
	usage: ${0##*/} [FINDOPTS]... [START]... [-- CMD [ARG]...]
	EOT
fi
find=(find -O2)

while [ $# -gt 0 ] && [[ "$1" != @([+-]*|!) ]] ;do
	find+=("$1")
	shift
done

find+=(-xdev)

case "${0##*/}" in
	ffx) find+=(-type f -a) ;;
	fdx) find+=(-depth -type d -a) ;;
	flx) find+=(-type l -a) ;;
	*) : ;;
esac

find+=('(' -true)

while [ $# -gt 0 ] ;do
	if [ "$1" = '--' ] ;then
		shift
		break
	else
		case "$1" in
			+n) find+=('!') ;&
			-n) find+=(-name "$2")    ; shift 2 ;;
			+N) find+=('!') ;&
			-N) find+=(-name "*$2*")  ; shift 2 ;;
			+i) find+=('!') ;&
			-i) find+=(-iname "$2")   ; shift 2 ;;
			+I) find+=('!') ;&
			-I) find+=(-iname "*$2*") ; shift 2 ;;
			+p) find+=('!') ;&
			-p) find+=(-path "$2")    ; shift 2 ;;
			+P) find+=('!') ;&
			-P) find+=(-path "*$2*")  ; shift 2 ;;
			+s) find+=('!') ;&
			-s) find+=(-size "$2")    ; shift 2 ;;
			+l) find+=('!') ;&
			-l) find+=(-links "$2")   ; shift 2 ;;
			*)  find+=("$1")	  ; shift 1 ;;
		esac
	fi
done

find+=(')' -print0)

if [ $# -ge 1 ] ;then
	exec "${find[@]}" 2>/dev/null |xargs -0r "$@"
elif [ -t 1 ] ;then
	exec "${find[@]}" 2>/dev/null |xargs -0r la -dF
else
	exec "${find[@]}" 2>/dev/null |xargs -0r ls -adF
fi
