#!/bin/sh
#
# Find files or directories with a simpler interface.
#
USAGE="fdir [-l] [-d DEPTH] [-f] [-x] [directory] [fileName]"
helpFile="$HOME/lbin/fname.txt"

# --- 1. Argument Parsing (getopt) ---
ARGS=$(getopt d:D:fFlLxXHh "$@")
if [ $? -ne 0 ]; then
    echo "BAD USAGE. Usage: $USAGE"
    if [ -f "$helpFile" ]; then cat "$helpFile"; fi
    exit 98
fi
set -- $ARGS

# --- 2. Option Variable Initialization ---
# Use separate flags for each behavior
doList=0     # Flag for -l (long list)
doExact=0    # Flag for -x (exact match)
fileType=""  # -f (file), -d (dir), or default
depth="X"    # Default: "X" (all depths)
cmdText=""   # For user feedback

# --- 3. Option Processing Loop ---
# This loop now correctly handles multiple flags
for i
do
	case "$i"
	in
		 -h| -H)
			if [ -f "$helpFile" ]; then cat "$helpFile"; fi
			exit 97;
			;;
		-d | -D )
			cmdText="$cmdText find Dirs at Depth: $2. "
			fileType="-type d" # -d implies directories
			depth=$2;
			shift 2; # Consume option (-d) and argument (DEPTH)
			;;
		-f | -F )
			cmdText="$cmdText find Files. "
			fileType="-type f" # -f implies files
			shift;
			;;
		-l | -L )
			cmdText="$cmdText List info. "
			doList=1
			shift;
			;;
		-x | -X )
			cmdText="$cmdText Exact match. "
			doExact=1
			shift;
			;;
		--)
			shift;
			break;
			;;
	esac
done

# --- 4. Set File Type Defaults ---
# If no fileType was set by -d or -f:
if [ -z "$fileType" ]; then
    if [ $doList -eq 1 ]; then
        # -l by itself lists files AND dirs
        fileType="-type f -o -type d" 
    else
        # Default behavior is to find directories
        fileType="-type d"
    fi
fi

# --- 5. Process Non-Option Arguments (Dir & Name) ---
argc="$#"
dirName=""
fileName=""

if [ $argc -eq 0 ]; then
	# No args: search for '*' in '.'
	dirName="."
	fileName="" # Will become '*'
elif [ $argc -eq 1 ]; then
	# One arg: assume it's fileName, search in '.'
	dirName="."
	fileName="$1"
elif [ $argc -ge 2 ]; then
	# Two+ args: dirName fileName
	dirName="$1"
	fileName="$2"
	if [ ! -d "$dirName" ]; then
		echo "ERROR: $dirName does not exist!!!(dirName)"
		exit 95;
	fi
fi

# --- 6. Set Wildcard Default ---
# Add wildcards unless -x (exact) was used
if [ $doExact -eq 0 ]; then
    if [ -z "$fileName" ]; then
        fileName="*"
    else
        # Add wildcards (prevents "foo*" from becoming "*foo**")
        case "$fileName" in
            # Don't add wildcards if they already exist
            \*|\?|\[*\]) ;; 
            *) fileName="*$fileName*" ;;
        esac
    fi
fi

# --- 7. Final Execution Block ---
echo "Looking for: $cmdText";
echo "  in directory: ($dirName)";
echo "  pattern: ($fileName)";

# Build the base find command
find_cmd="find ${dirName} ${fileType} "

# Add Depth if set
if [ "${depth}" != "X" ] ;
then
    # Use -maxdepth. Use -depth if your 'find' is older.
    find_cmd="${find_cmd} -maxdepth ${depth} "
fi

# Add File Name search
if [ ! -z "${fileName}" ] ;
then
    find_cmd="${find_cmd} -iname \"${fileName}\" "
fi

# Execute the command
if [ $doList -eq 1 ]; then
    # -l option: Use -exec ls -ld
    echo "Executing Long Listing (-l)..."
    eval "${find_cmd} -exec ls -ld {} \;"
    rtn="$?"
else
    # Default: Use -print
    echo "Executing print format..."
    eval "${find_cmd} -print"
    rtn="$?"
fi

echo "RTN=$rtn"
