#!/bin/sh
# fname: find files or directories by name with options
# Usage: fname [options] [directory] fileName
# Options:
#   -h          Show help
#   -d          Search for directories only
#   -f          Search for files only (default)
#   -l          Long listing (ls -l)
#   -n          Files with no extension
#   -x          Exact match (no wildcards)
#   -j          JSON output (machine-readable)

helpFile="$HOME/lbin/fname.txt"

show_help() {
    if [ -f "$helpFile" ]; then
        cat "$helpFile"
    else
        cat <<EOF
Usage: fname [options] [directory] fileName
Options:
  -h    Show help
  -d    Search for directories only
  -f    Search for files only (default)
  -l    Long listing (ls -l)
  -n    Files with no extension
  -x    Exact match (no wildcards)
  -j    JSON output
EOF
    fi
    exit 0
}

# Defaults
fileType="f"
longListing=0
exactMatch=0
noExt=0
jsonOut=0

# Parse options
while getopts "hdflnxj" opt; do
    case "$opt" in
        h) show_help ;;
        d) fileType="d" ;;
        f) fileType="f" ;;
        l) longListing=1 ;;
        n) noExt=1 ;;
        x) exactMatch=1 ;;
        j) jsonOut=1 ;;
        *) show_help ;;
    esac
done
shift $((OPTIND-1))

# Args: [directory] fileName
if [ $# -eq 0 ]; then
    show_help
elif [ $# -eq 1 ]; then
    dirName="."
    fileName="$1"
else
    dirName="$1"
    fileName="$2"
fi

# Handle no-extension mode
if [ $noExt -eq 1 ]; then
    results=$(find "$dirName" -type f ! -name "*.*")
else
    # Handle exact vs wildcard
    if [ $exactMatch -eq 1 ]; then
        pattern="$fileName"
    else
        pattern="*$fileName*"
    fi

    if [ $longListing -eq 1 ]; then
        results=$(find "$dirName" -type "$fileType" -iname "$pattern" -exec ls -ld {} +)
    else
        results=$(find "$dirName" -type "$fileType" -iname "$pattern" -print)
    fi
fi

# Output
if [ $jsonOut -eq 1 ]; then
    # Convert results into JSON array
    echo "$results" | awk 'BEGIN{print "["} 
        {gsub(/"/,"\\\""); printf "%s\"%s\"", sep, $0; sep=","} 
        END{print "]"}'
else
    echo "$results"
fi

