#!/bin/sh

usage() {
    echo "This recipe will download file first and then pass it to transmission"
    echo "Might be used to pass login/password cookie for downloading"
    echo "and then passing the file to transmission"
    echo "$0 [HOST[:PORT]] [USERNAME:PASSWORD]"
    echo
    echo "[HOST[:PORT]]        optional, transmission host and maybe port"
    echo "[USERNAME:PASSWORD]  optional, transmission web username and password"
}

if [ -z "$LEECH_DOWNLOADS_DIR" ]; then
    usage
    exit 1
fi

HERE="$(dirname "$0")"
LEECH_DEFAULT="$HERE/leech-default"
LEECH_TRANSMISSION="$HERE/leech-transmission"
OUTPUT="$LEECH_URL"

# run default, it will print output filename to stdout,
# but skip magnet links
#
echo $LEECH_URL | grep -e "^magnet:" - >/dev/null
if [ $? -ne 0 ]; then
    OUTPUT="$($LEECH_DEFAULT)"
    RET=$?

    # exit if default failed, preserve return value
    [ "$RET" -ne "0" ] && exit $RET
fi

trap "rm -f '$OUTPUT'" 1 2 3 15

# run transmission recipe changing URL to $OUTPUT,
# command line arguments naturally fits leech-transmission
#
(LEECH_URL="$OUTPUT" LEECH_TARGET_DIR="$LEECH_TARGET_DIR" $LEECH_TRANSMISSION "$@")
RET=$?

# cleanup
#
rm -f "$OUTPUT"

# exit preserving return value of last recipe
exit $RET
