#!/bin/bash
#author:Wos
#1337x.to Terminal
#default sort by seeder
HTMP="/tmp/1337xto.html"
TTMP="/tmp/1337xto_title.txt" 
SZTMP="/tmp/1337xto_size.txt"
LTMP="/tmp/1337xto_maglink.txt"
DOMAIN="https://1337x.to"
HS=""
CK="cf_clearance=TFNWOjM4PEjK8tPL7LYgAq1UaKionGaryVLMF68cHLw-1715682214-1.0.1.1-kglwItzJzi6f7A5R46urckWeRxPS.aJMw2oRBhxgYSbyAJ0zUEs8mRHWdcOUAuPYj90Vc3Q0pgC8R14FWBOFPg"
PXY="-x http://127.0.0.1:7891"
function logo()
{
    echo -e "\033[96;40m"
    base64 -d <<<"H4sIAAAAAAAAA4WLsRHAMAwCe01BGVcspDsW8fAB+ZIiTWQfRvCGoO/giTBLETuGr6DRtIVJQl5r
wyduBG7Pk3g67DD+vaKWILkNHUbDKIw4QgURW5eW606Iwv/UDZB9CGbYAAAA"|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
curl ${PXY} --cookie "${CK}" -s ${DOMAIN%%/}"/sort-search/"${KW// /%20}"/seeders/desc/1/" > ${HTMP} 
if [ $? == 0 ]; then
    break
fi
sleep 1
done
cat ${HTMP} |grep -E '<td class="coll-1 name">'|awk -F\> '{print $7}'|awk -F\< '{print $1}'|head -n 40 > ${TTMP} 
cat ${HTMP} |grep -E '<td class="coll-4 size'|awk -F\> '{print $2}'|awk -F\< '{print $1}'|head -n 40 > ${SZTMP}
cat ${HTMP} |grep -E '<td class="coll-1 name">'|awk -F\> '{print $6}'|awk -F\" '{print $2}'|head -n 40 > ${LTMP} 
}
getlink
while :; 
do
clear
logo
paste -d' ' ${SZTMP} ${TTMP}|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 -ne "    Select Resource ID or Search:\033[0m"
read -r input
echo -ne "\033[?25l"
NUM=$(cat ${TTMP}|wc -l)
if [[ $input =~ ^-?[0-9]+$ ]] && (( $input > 0 && $input <= $NUM )); then
    HS=$input 
    LINK=${DOMAIN%%/}$(sed -n "${input}p" "${LTMP}") 
    curl ${PXY} -s ${LINK}|grep -oE 'magnet:.*Magnet Download'|awk -F\" '{print $1}'|xclip -selection clipboard
    echo -e "\033[93;40m    Magnet Link Already Copy to Clipboard\033[0m"
    sleep 1 
    echo -e "\033[?25h"
elif [[ -z "$input" ]]; then
    continue
else
    HS=""
    KW=$input
    getlink
    continue
fi
done