#!/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"
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

export DOWNLOAD_RECIPE="../tests/sbin/target-dir-test"

# test that TARGET_DIR is unset by default
#
($TOOL >/dev/null)

GOT_TARGET_DIR=$(cat "$DOWNLOADS_DIR"/leech_target_dir)
NEED_TARGET_DIR=""

[ "$GOT_TARGET_DIR" = "$NEED_TARGET_DIR" ] && echo -n '.' || assert "0 -eq 1"

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

# test TARGET_DIR can be set from environment
#
(TARGET_DIR="set from env" $TOOL >/dev/null)

GOT_TARGET_DIR=$(cat "$DOWNLOADS_DIR"/leech_target_dir)
NEED_TARGET_DIR="set from env"

[ "$GOT_TARGET_DIR" = "$NEED_TARGET_DIR" ] && echo -n '.' || assert "0 -eq 2"

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

# test target dir can be set from config
#
export CONFIG_DIR="$HERE/conf-target-dir"
CONFIG="$HERE/../sbin/leech-config"
. "$CONFIG"

echo -n $LUNCH >"$FOODS"  # put processed XML URL into foods, -n to check proces

($TOOL >/dev/null)

GOT_TARGET_DIR=$(cat "$DOWNLOADS_DIR"/leech_target_dir)
NEED_TARGET_DIR="set from config" # TARGET_DIR is unset by default

[ "$GOT_TARGET_DIR" = "$NEED_TARGET_DIR" ] && echo -n '.' || assert "0 -eq 3"

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