#!/bin/sh

# Author: stangri based on original by discrucio <https://forum.openwrt.org/viewtopic.php?pid=254981#p254981>

usage() {
    echo "This is an aria2 specific download recipe for leech"
    echo
    echo "Please ensure that aria2 is running with RPC enabled:"
    echo "aria2c --enable-rpc --rpc-listen-all=true --rpc-allow-origin-all"
    echo
    echo "$0 HOST:PORT [RPC_SECRET]"
    echo
    echo "HOST:PORT            mandatory, aria2 JSON-RPC host and port"
    echo "[RPC_SECRET]         optional, aria2 RPC secret authorization token"
}

invoked_usage() {
    echo "LEECH_URL is empty. Please use this recipe via the "$CONFIG_DIR"/default file"
    echo "or specify the shell variable in advance."
}

HOST_PORT=$1
RPC_SECRET=$2

[ -z "$HOST_PORT" ] && usage && exit 1
[ -z "$LEECH_URL" ] && invoked_usage && exit 2

ARIA2_SERVER="http://"$HOST_PORT"/jsonrpc"
ARIA2_PARAM='{"id":null,"jsonrpc":"2.0","method":"aria2.addUri","params":["token:'"$RPC_SECRET"'",["'$LEECH_URL'"]'

[ -z "$LEECH_TARGET_DIR" ] && ARIA2_PARAM=$ARIA2_PARAM']}' || ARIA2_PARAM=$ARIA2_PARAM',{"dir":"'$LEECH_TARGET_DIR'"}]}'

exec curl -X POST -H 'Content-Type: application/json' -H 'Accept: application/json' -d $ARIA2_PARAM $ARIA2_SERVER
