#!/bin/bash
#author:Wos
#torrentgalaxy.to Terminal
#default sort by seeder
HTMP="/tmp/tgt.html"
TTMP="/tmp/tgt_title.txt"
SZTMP="/tmp/tgt_size.txt"
LTMP="/tmp/tgt_link.txt"
HS=""
PXY="-x http://127.0.0.1:7891"
DOMAIN="https://torrentgalaxy.to/"
function logo()
{
    echo -e "\033[96;40m"
    base64 -d <<<"H4sIAAAAAAAAA32QUQoEIQxD/z1F/mYHhF5g2ZMUMgfp4adp9XMtEpM8FBHEYXiMmhEIgqRoass2
C+qgNOPGLQmGKkvjgYssqZhGXaUH0bp2hxtMEaEXBD68K3aHOta2oEzr2n/AV6/TBXAyF02xOjUs
yGg4ITPZxaTRnN5gnL6wJnT7fzBeZ0cY1YYBAAA="|gunzip
    echo -e "\033[0m"
}

function usage(){
   logo
   echo  "usage:`basename $0` [keyword]"
   echo ""
   exit -1
}

if [ $# == 0 ]; then
   usage
elif [ $# == 1 ] && [ $1 == "-h" ];then
   usage
fi

KW=$@ 
function getlink(){
while :;
do
clear
logo
echo -ne "\033[?25l"
echo -ne "     Loading..."
curl --connect-timeout 3 --compressed ${PXY} -s ${DOMAIN%%/}"/torrents.php?search="${KW// /+}"&sort=seeders&order=desc" > ${HTMP} 2>/dev/null
if [ $? == 0 ]; then
    echo -ne "\033[?25h"
    break
fi
sleep 1
done
cat ${HTMP} |grep -oE "<a class='txlight' title=.*\" href=\""|awk -F\" '{print $2}'|head -n 40 > ${TTMP} 
cat ${HTMP} |grep -oE "<a class='txlight' title=.*\""|grep -oE 'Size <span.*</span>'|awk -F\> '{print $2}'|awk -F\< '{print $1}'|head -n 40 > ${SZTMP}
cat ${HTMP} |grep -oE "<a class='txlight' title=.*\""|grep -oE 'magnet:.*" role='|awk -F\" '{print $1}'|head -n 40 > ${LTMP} 
}

getlink
while :;
do
clear
logo
paste -d' ' ${SZTMP} ${TTMP}|sed "s/&#39;/\'/g"|nl
echo -e "\033[96;40m"
if [[ ! -z "$HS" ]]; then
    echo -ne "    [^c:Exit]"
    echo " History Resource ID:$HS"
else
    echo -e "    [^c:Exit]"
fi
echo -n "    Select Resource ID or Search:"
echo -ne "\033[0m"
read -r input
NUM=$(cat ${TTMP}|wc -l)
if [[ $input =~ ^-?[0-9]+$ ]] && (( $input > 0 && $input <= $NUM )); then
    HS=$input
    xclip -selection clipboard <(sed -n "${input}p" "${LTMP}") &> /dev/null
    echo -e "\033[96;40m"
    echo "    Magnet Link Already Copy to Clipboard"
    echo -e "\033[0m"
    sleep 1 
elif [[ -z "$input" ]]; then
    continue
else
    HS=""
    KW=$input
    getlink
    continue
fi
done