#!/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-recipe"
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 results into no cookie option
#
($TOOL >/dev/null)

# sink should contain info on last file in feed
#
GOT_DOWNLOADS_DIR=$(cat "$DOWNLOADS_DIR"/leech_downloads_dir)
GOT_CONFIG_DIR=$(cat "$DOWNLOADS_DIR"/leech_config_dir)
GOT_FEED_URL=$(cat "$DOWNLOADS_DIR"/leech_feed_url)
GOT_URL=$(cat "$DOWNLOADS_DIR"/leech_url)
GOT_URL_MD5=$(cat "$DOWNLOADS_DIR"/leech_url_md5)
GOT_TITLE=$(cat "$DOWNLOADS_DIR"/leech_title)
GOT_PUBDATE=$(cat "$DOWNLOADS_DIR"/leech_pubdate)
GOT_TIMEOUT=$(cat "$DOWNLOADS_DIR"/leech_timeout)
GOT_TARGET_DIR=$(cat "$DOWNLOADS_DIR"/leech_target_dir)

NEED_URL="file://$HERE/files/crap.wmv"
NEED_URL_MD5=$(echo -n "$NEED_URL" | md5sum | cut -c 1-32)
NEED_TITLE="title wmv"
NEED_PUBDATE="Sat, 11 Aug 2032 16:34:46 +0000"
NEED_TARGET_DIR="set from config"

# manual "asserts" of strings
[ "$GOT_DOWNLOADS_DIR" = "$DOWNLOADS_DIR" ] && echo -n '.' || assert "0 -eq 1"
[ "$GOT_CONFIG_DIR" = "$CONFIG_DIR" ] && echo -n '.' || assert "0 -eq 1"
[ "$GOT_FEED_URL" = "$LUNCH" ] && echo -n '.' || assert "0 -eq 1"
[ "$GOT_URL" = "$NEED_URL" ] && echo -n '.' || assert "0 -eq 1"
[ "$GOT_URL_MD5" = "$NEED_URL_MD5" ] && echo -n '.' || assert "0 -eq 1"
[ "$GOT_TITLE" = "$NEED_TITLE" ] && echo -n '.' || assert "0 -eq 1"
[ "$GOT_PUBDATE" = "$NEED_PUBDATE" ] && echo -n '.' || assert "0 -eq 1"
[ "$GOT_TARGET_DIR" = "$NEED_TARGET_DIR" ] && echo -n '.' || assert "0 -eq 1"

assert "$GOT_TIMEOUT -eq 30"

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