#!/bin/sh

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

DEFAULT_CONFIG_DIR="/etc/leech"

usage() {
    echo "Usage: CONFIG_DIR=\"<DIR>\" $0 \"<FILENAME>\" \"[FEEDURL]\""
    echo "Or you could omit CONFIG_DIR to use \"$DEFAULT_CONFIG_DIR\" by default"
    echo
    echo "This tool will test passed filename (and optionally feed) against your configuration files and tell if file will be downloaded with current configuration or not"
    echo
    echo "Arguments:"
    echo "  <FILENAME>  filename to match against rules in CONFIG_DIR"
    echo "  [FEEDURL]   optional, URL of the feed if you're linking filters to feed"
}

# check arguments count
#
if [ $# -lt 1 ]; then
    usage
    exit 1
fi

if [ -z "$CONFIG_DIR" ]; then
    CONFIG_DIR="$DEFAULT_CONFIG_DIR"
fi

HERE="$(dirname "$0")"
WILD_MAGIC="$HERE/leech-wild-magic"
CONFIG="$HERE/leech-config"

if [ ! -f $CONFIG ]; then
    echo "ERROR: No config file found at $CONFIG"
    usage
    exit 1
fi

. "$CONFIG"

FILENAME=$1
FEED_URL=$2

SEARCH_STRING=$(echo "$FEED_URL $FILENAME" | sed -r -e 's/^ *//g ' -e 's/ *$//g')

LINES=$(echo $SEARCH_STRING | DOWNLOADS="$DOWNLOADS" \
    REVERSE_DOWNLOADS="$REVERSE_DOWNLOADS" \
    WILD_DOWNLOADS="$WILD_DOWNLOADS" $WILD_MAGIC)

if [ ! -z "$LINES" ]; then
    echo -n "OK, '$FILENAME' will be downloaded "
    [ ! -z "$FEED_URL" ] && echo -n "from '$FEED_URL' "
    echo "according to rules in '$WILD_DOWNLOADS' and '$DOWNLOADS'"
    exit 0
else
    echo -n "Nope. Either '$FILENAME' doesn't match any pattern in "
    echo -n "'$WILD_DOWNLOADS' (or '$DOWNLOADS') or it is excluded "
    echo "by filters in '$REVERSE_DOWNLOADS'"
    exit 1
fi
