#!/usr/bin/env bash
# ollie:parallel read
# description: Find files by name/path pattern, sorted by modification time (newest first)
# Args: <pattern> [path]

pattern="$1"
search_path="${2:-$PWD}"

[ -z "$pattern" ] && echo "usage: file_glob <pattern> [path]" && exit 1

if [ ! -d "$search_path" ]; then
    echo "STATUS=error"
    echo "error: path is not a directory: $search_path"
    exit 1
fi

# collect matches and sort by mtime descending
rg_out=$(rg --no-config --files -g "$pattern" "$search_path" 2>&1)
rg_exit=$?
if [ $rg_exit -gt 1 ]; then
    echo "STATUS=error"
    echo "error: $rg_out"
    exit 1
fi
if [ -z "$rg_out" ]; then
    echo "STATUS=no_matches MATCH_COUNT=0"
    echo "no matches"
    exit 0
fi

sorted=$(echo "$rg_out" \
    | xargs -d '\n' stat --printf '%Y\t%n\n' 2>&1 \
    | sort -rn \
    | cut -f2-)

count=$(echo "$sorted" | wc -l | tr -d ' ')
echo "STATUS=ok MATCH_COUNT=$count"
echo "$sorted"
