#!/bin/sh

[ ! -z "$LEECHT" ] && set "$LEECHT"

. $(dirname $0)/assert.sh

HERE=$(cd "$(dirname "$0")" && pwd)  # current dir
TOOL="$HERE/../sbin/leech"
CONFIG="$HERE/../sbin/leech-config"

SOURCE="$HERE/files/rss.xml"
PROCESSED="$HERE/files/processed.xml"
LUNCH="file://$PROCESSED"  # file/processed.xml

export CONFIG_DIR="$HERE/conf-cookies"
export DOWNLOADS_DIR="$HERE/dl"

. "$CONFIG"

rm -f "$DOWNLOADS_DIR"/*
rm -f "$DOWNLOADS_DIR/.leech.db"
rm -f "$PROCESSED"
rm -f "$FOODS"

echo -n $LUNCH >"$FOODS"  # put processed XML URL into foods, -n to check proces
cat "$SOURCE" \
	| sed -e "s|NOW|$(date -R)|" \
        | sed -e "s|file://.|file://$HERE|" \
	>"$PROCESSED"  # replace file://./files with absolute paths for cURL

# test that no cookie set resulting in no cookie passed to DL script
#
($TOOL >/dev/null)
assert "-z $(cat "$DOWNLOADS_DIR/cookie-jar")"

rm -f "$DOWNLOADS_DIR"/*
rm -f "$DOWNLOADS_DIR/.leech.db"

# for each download a special recipe should be called
# to check that cookie is set
#
export COOKIE="?hello=1&world=1"
($TOOL >/dev/null)
# test that $COOKIE passed to leech was correctly passed to recipe
assert "$(cat "$DOWNLOADS_DIR/cookie-jar" | grep "$COOKIE" | wc -l) -eq 1"

rm -f "$DOWNLOADS_DIR"/*
rm -f "$DOWNLOADS_DIR/.leech.db"

# include whitespace into cookie to check if entire argument ended up in cookie-jar
#
export COOKIE="/home/alex/coo kie.txt"
($TOOL >/dev/null)
assert "$(cat "$DOWNLOADS_DIR/cookie-jar" | grep "$COOKIE" | wc -l) -eq 1"

rm -f "$DOWNLOADS_DIR"/*
rm -f "$DOWNLOADS_DIR/.leech.db"

# include whidcard into cookie (point to this dir -> expands into list of tests)
#
export COOKIE="$HERE/"'*.sh'
($TOOL >/dev/null)
assert "$(cat "$DOWNLOADS_DIR/cookie-jar" | grep -F "$COOKIE" | wc -l) -eq 1"

# cleanup
#
rm -f "$DOWNLOADS_DIR"/*
rm -f "$DOWNLOADS_DIR"/.leech.db
rm -f "$PROCESSED"
rm -f "$FOODS"
unset COOKIE
