#!/bin/sh
#author:Wos
#Pirate Bay Terminal
#choose a fastest domain from pirvatebay mirror
#https://piratebay-proxylist.com/
#default sort by seeder
HTMP="/tmp/pbt.html"
TTMP="/tmp/pbt_title.txt"
SZTMP="/tmp/pbt_size.txt"
LTMP="/tmp/pbt_maglink.txt"
DOMAIN="https://thepiratebay7.com/"
HS=""
PXY="-x http://127.0.0.1:7891"
function logo()
{
    echo -e "\033[96;40m"
    base64 -d <<<"H4sIAAAAAAAAA41RSQ7EMAi75xW+TSNVyocquQ/h8YMhZFophyEJBAN2F9AN8L3sd8/a27gD8WZQ
1kz+OtjpM7ENpot3mvKOQGNSWERLqJyfYkBxNPF05zB8yAHewTckh1TFRHNJz7LsA5rCrSwZHt3x
zBw1dzBigijViXIxV3npPdfsburXO0a8yJPm3nd8FYphoSdmb5Q1EGp5OGN209rmX+zNQuV/a1/h
IK0xHAIAAA=="|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} -s ${DOMAIN%%/}"/search/"${KW}"/1/7/0" > ${HTMP} 
cat ${HTMP} |grep -oE 'class="detLink" title=".*</a>'|awk -F\> '{print $2}'|awk -F\</a '{print $1}'|head -n 40 > ${TTMP} 
cat ${HTMP} |grep -oE 'class="detDesc">.*, UL'|awk '{print $4}'|sed "s/&nbsp;/ /g"|head -n 40 > ${SZTMP}
cat ${HTMP} |grep -oE 'href="magnet:.*" title="Download'|awk -F\" '{print $2}'|head -n 40 > ${LTMP} 
if [ -s "${TTMP}" ]; then
    break
fi
done

}
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
read -e -r -p "    Select Resource ID or Search:" input
echo -e "\033[0m"
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[?25l\033[93;40m    Magnet Link Already Copy to Clipboard\033[0m"
    sleep 1 
    echo -ne "\033[?25h"
elif [[ -z "$input" ]]; then
    continue
else
    HS=""
    KW=$input
    getlink
    continue
fi
done