#!/usr/bin/env bash
# description: Search memories by keyword, tag, or title
# Args: <query>

[ -z "$*" ] && echo "usage: memory_recall <query>" && exit 1

mount="${OLLIE:-$HOME/mnt/ollie}"
mem_dir="$mount/m"

if [ ! -d "$mem_dir" ]; then
    echo "error: memory directory does not exist: $mem_dir"
    exit 1
fi

query="$*"

# Search filenames (title/tag match) and file bodies
matches=$(grep -ril "$query" "$mem_dir" 2>&1)
grep_exit=$?
if [ $grep_exit -gt 1 ]; then
    echo "error: $matches"
    exit 1
fi

if [ -z "$matches" ]; then
    echo "no matches for: $query"
    exit 0
fi

while IFS= read -r file; do
    echo "=== $(basename "$file") ==="
    cat "$file" || echo "error: could not read $file"
    echo
done <<< "$matches"
