#!/bin/sh

#shellcheck disable=SC2059

c_red="\033[1;31m"
c_green="\033[1;32m"
c_yellow="\033[1;33m"
c_cyan="\033[1;36m"
c_reset="\033[0m"

down() {
	tput reset
	info_$os "Torrent: Downloading"
	aria2c --file-allocation=trunc -d "$download_dir" --select-file="$2" --seed-time=0 --seed-ratio='0.0' --summary-interval=0 "$1" && info_$os "Torrent: Download complete" && return 0
	error_$os "Torrent: Error!!"
}

magnet="$1"
if [ "$(uname -o)" = "Android" ]; then
	os="droid"
	script_dir="$HOME/.shortcuts"
	download_dir="/sdcard"
	[ -z "$magnet" ] && magnet="$(termux-clipboard-get)"
else
	os="linux"
	script_dir="$HOME/repos_scripts"
	download_dir="$HOME/Softwares"
	[ -z "$magnet" ] && magnet="$(wl-paste)"
	terminal="${TERMINAL:-foot}"
	prefix="setsid -f $terminal -e"
	pgrep -af "$0" | grep -q "$terminal" || {
		$prefix "$0" "$magnet"
		exit 0
	}
fi

#import generic functions
# shellcheck source=./.functions
. "$script_dir/.functions"

filepath="$HOME/.cache"
#check if the url is magnet
! printf "%s" "$magnet" | grep -qE "magnet:\?xt=urn:btih:|\.torrent$" && error_$os "Not a valid magnet link!" && exit 0

# check if the variable is actuall magnet-link or file
if printf '%s' "$magnet" | grep -qE "\.torrent$"; then
	filepath="$(dirname "$magnet")"
	file="$(basename "$magnet")"
	is_file=1
fi

echo "$magnet"
printf "${c_yellow}Download>>\n${c_green}[f]ull torrent\n${c_cyan}[p]artial torrent \n${c_red}[q]uit"
printf "${c_reset}\n\tenter choice:"
[ -z "$2" ] && read -r ch || ch=$2
case $ch in
	f)
		down "$magnet"
		;;
	p)
		if [ -z "$is_file" ]; then
			file="$(printf "%s" "$magnet" | sed -nE 's|.*urn:btih:([^&]*).*|\1|p' | tr '[:upper:]' '[:lower:]').torrent"
			{ [ -f "$filepath/$file" ] && [ ! -f "$filepath/$file.aria2" ]; } || aria2c --dir="$filepath" --bt-metadata-only=true --bt-save-metadata=true "$magnet" -o "$file"
		fi
		tput reset
		aria2c --show-files=true "$filepath/$file"
		printf "${c_cyan}Enter file idx(default=all): "
		read -r ind
		down "$filepath/$file" "$ind"
		rm -f "$filepath/$file"
		;;
	q)
		exit 0
		;;
esac
