#!/usr/pkg/bin/bash

if [[ -n $QUERY_STRING ]]
then
       set -- $QUERY_STRING
elif [[ -n $SEARCHREQUEST ]]
then
       set -- $SEARCHREQUEST
else
       exit 1
fi

db=cache/manifest

# Create or use a database to avoid consent accidents.
# Should be just a find(1) output.
print_files() {
       if [[ -f "${db}" ]]
       then
               local x=$(date +%s)             # Now
               local y=$(stat -f '%m' "${db}") # Modified date of $db
       fi

       if [[ ! -e "$db" ]] || (( x-y > 60 ))
       then
               /usr/pkg/bin/gfind -L .. \
                       -mindepth 1 \
                       -perm -004 \
                       -type f \
                       -printf "%P\n" \
                       | /usr/bin/tee "${db}"
       else
               local REPLY
               read -rd '' < "${db}"
               echo "${REPLY}"
       fi
}

format_map() {
       /usr/bin/awk '
               BEGIN { FS = "/" }
               { printf "i%30s : %-30s\n", $NF, $0 }'
}

main() {
       print_files | /usr/bin/grep -ie "${*}" | format_map
}

main "${@}"