#!/bin/sh

# Author: Aleksey Tulinov <aleksey.tulinov@gmail.com>

usage() {
    echo "This is leech magic file, consult the spellbook for usage options"
    # for spellbook readers:
    #
    # DOWNLOADS=<PATH_TO_DOWNLOADS> \
    # WILD_DOWNLOADS=<PATH_TO_WILD_DOWNLOADS> \
    # REVERSE_DOWNLOADS=<PATH_TO_REVERSE_DOWNLOADS> \
    # leech-wild-magic
    #
    # this script will match all requested downloads (from both files)
    # as they all were filled in $DOWNLOADS in grep-ready format
    #
    # for example:
    #
    # $ echo "hello world" >$WILD_DOWNLOADS \
    #   && echo "world.*hello" >$DOWNLOADS \
    #   && cat $FILES | ... leech-wild-magic
    #
    # would print anything matching:
    #
    # 1) hello.*world
    # 2) world.*hello
    #
    # reverse matching rules are applied to the result of this matching
}

if [ -z "$DOWNLOADS" ] || [ -z "$WILD_DOWNLOADS" ] || [ -z "$REVERSE_DOWNLOADS" ]; then
  usage
  exit 1
fi

MERGED_FILE=$(mktemp -t leech.wild.XXXXXX)
REVERSE_FILE=$(mktemp -t leech.reverse.XXXXXX)
trap "rm -f '$MERGED_FILE' '$REVERSE_FILE'" 1 2 3 15

# escape dots, question marks in string
# only appliable to wild downloads, usual regexes should be escaped manually
SED_ESCAPE_REGEX='s/[^a-zA-Z0-9 ]/\\&/g'
# transform whitespaces into .*
SED_WILD_TO_REGULAR="s/ +/.*/g"

# transform wilds into regexes
#
cat "$WILD_DOWNLOADS" \
    | grep -v -e '^#' -e '^$' \
    | sed -r -e "$SED_ESCAPE_REGEX" -e "$SED_WILD_TO_REGULAR" >"$MERGED_FILE" 2>/dev/null

# join with usual regexes
#
cat "$DOWNLOADS" | grep -v -e '^#' -e '^$' >>"$MERGED_FILE" 2>/dev/null

# create reverse matching file
#
cat "$REVERSE_DOWNLOADS" | grep -v -e '^#' -e '^$' >"$REVERSE_FILE" 2>/dev/null

# match stdin
#
# busybox' grep is having some odd issue with -f when patterns
# file is empty (0 bytes), so [ -s ] is required
#
# if match patterns are null - produce empty output,
# if reverse-match patterns are null - just proxy stdin
#
([ -s "$MERGED_FILE" ] && grep -i -f "$MERGED_FILE" || echo -n "") \
    | ([ -s "$REVERSE_FILE" ] && grep -i -v -f "$REVERSE_FILE" || cat -)

rm -f "$MERGED_FILE" "$REVERSE_FILE"
