#!/bin/sh
#
# spam-ascii — cat a file from ~/ascii given a partial/fuzzy name.
#
# Resolution order:
#   1. exact filename match: ~/ascii/<pattern>
#   2. exact name + common extension: <pattern>.txt, .ans, .asc
#   3. first case-insensitive *substring* match (sorted alphabetically)
#
# If nothing matches, prints a friendly error to stdout and exits non-zero.
# Used by the irssi /spam alias, which pipes our stdout as channel messages.

set -eu

pattern=${1:-}
if [ -z "$pattern" ]; then
    echo "usage: spam-ascii <pattern>"
    exit 1
fi

dir="$HOME/ascii"

# 1 + 2. Try exact name, then exact + common ASCII-art extensions.
for candidate in \
        "$dir/$pattern" \
        "$dir/$pattern.txt" \
        "$dir/$pattern.ans" \
        "$dir/$pattern.asc"; do
    if [ -f "$candidate" ]; then
        cat "$candidate"
        exit 0
    fi
done

# 3. First case-insensitive substring match.
match=$(find "$dir" -maxdepth 1 -type f -iname "*$pattern*" 2>/dev/null \
        | sort \
        | head -n1)

if [ -n "$match" ]; then
    cat "$match"
    exit 0
fi

echo "no match in ~/ascii for: $pattern"
exit 1
