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

STUB_DB="$HERE/files/leech.db"
EMPTY_LUNCH="$HERE/files/empty_lunch.xml"

LUNCH="file://$EMPTY_LUNCH"  # files/empty_lunch.xml

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

. "$CONFIG"

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

# write path to (empty) lunch into foods
#
echo -n $LUNCH >"$FOODS"

# sanity check: $DOWNLOADS_DIR is actually empty before test, etc
#
assert "$(ls $DOWNLOADS_DIR | wc -l) -eq 0"

# this test assume that current date is between 2000 and 2035
#
NOW=$(date -u +%s)
assert "$NOW -gt 946684800"
assert "$NOW -lt 2082758399"

# write test db into actual db and check that it fit this test
#
cat "$STUB_DB" > "$DOWNLOADS_DIR"/.leech.db
assert "$(cat $DOWNLOADS_DIR/.leech.db | wc -l) -eq 3"

# nothing should be downloaded, but db should be cleared
#
($TOOL >/dev/null)

# "0" x32 is from 2000 - should be removed
# "1" x32 is from 2003 - should be removed
# "2" x32 is from 2035 - should be kept
#
assert "$(cat $DOWNLOADS_DIR/.leech.db | wc -l) -eq 1"
assert "$(cat $DOWNLOADS_DIR/.leech.db | grep 22222222222222222222222222222222 | wc -l) -eq 1"

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