#!/bin/sh
#author:Wos
#universal downloader
WORK_DIR=$(dirname $0)
TRACKERPATH=${WORK_DIR}/trackers_all_ips.txt
TMPTORRENT=/tmp/temp.torrent
#test link
if [[ "$#" == 0 ]]; then
    LINK=$(xclip -selection clipboard -o)
    if [[ "$LINK" =~ ^http ]] || [[ "$LINK" =~ ^magnet ]]; then
        break
    else
        echo -e "Invalid Link"
        exit -1
    fi
elif [[ "$1" =~ ^http ]] || [[ "$1" =~ ^magnet ]]; then
    LINK=$1
else
    echo -e "Invalid Link"
    exit -1
fi
echo $LINK
PXY=""
PPXY=""
read -e -r -p "Whether to enable proxy?Y/N" input
if [[ "${input}" == "y" ]] || [[ "${input}" == "Y" ]]; then
    PXY="-x http://127.0.0.1:7891"
    PPXY="--all-proxy=http://127.0.0.1:7891"
fi


function get_tracker_list(){
    read -e -r -p "Whether to update tracker list?Y/N" input
    if [[ "${input}" == "y" ]] || [[ "${input}" == "Y" ]]; then
        curl --connect-timeout 3 ${PXY} -s "https://ngosang.github.io/trackerslist/trackers_all_ip.txt"|xargs|tr ' ' ',' > ${TRACKERPATH} || curl --connect-timeout 3 -x http://127.0.0.1:7891 -s "https://ngosang.github.io/trackerslist/trackers_all_ip.txt"|xargs|tr ' ' ',' > ${TRACKERPATH}
    fi
}

if [[ "${LINK}" =~ ^magnet ]]; then
    get_tracker_list
    aria2c ${PPXY} -U80K --seed-time=0 --bt-tracker-connect-timeout=90 --bt-tracker-timeout=120 --bt-tracker-interval=60 --file-allocation=none "${LINK}" --bt-tracker=$(cat ${TRACKERPATH})
    exit -1
elif [[ "${LINK}" == *Torrent* ]] || [[ "${LINK}" =~ "*.torrent$" ]] || [[ "${LINK}" == *torrent* ]]; then
    get_tracker_list
    curl ${PXY} -s "${LINK}" > ${TMPTORRENT}
    aria2c ${PPXY} -U80K --seed-time=0 --bt-tracker-connect-timeout=90 --bt-tracker-timeout=120 --bt-tracker-interval=60 --file-allocation=none "${TMPTORRENT}" --bt-tracker=$(cat ${TRACKERPATH})
    exit -1
else
    aria2c --check-certificate=false --file-allocation=none "${LINK}" -c -x8 -s8 -k 1M
    exit -1
fi