#!/bin/sh
#author:Wos
#yts.mx Terminal
#default sort by seeder
HTMP="/tmp/yts.html"
TTMP="/tmp/yts_title.txt"
LTMP="/tmp/yts_link.txt"
MLTMP="/tmp/yts_maglink.txt"
HS=""
PXY="-x http://127.0.0.1:7891"
DOMAIN="https://yts.mx/"
function logo()
{
    echo -e "\033[96;40m"
    base64 -d <<<"H4sIAAAAAAAAA41Qyw7DIAy78xW+0UqT8jc7Ibkfko9fbMpUdT0sKA9DbAgkAE5zxsL4Nd5QGxgI
hDVCtATSKCWHbyjfuLuGNxLZivwuOqrGUMuQbKGSqrpLrhOHkHo6fR0PmG3eGYu9X1Eo5cPamItN
9wtr3MBEekjOOXI5z1xnL9Xt4W/+t/YBH3AUHnQBAAA="|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%%/}"/browse-movies/"${KW// /%20}"/all/all/0/seeds/0/all" > ${HTMP} 
cat ${HTMP} |grep -oE 'class="browse-movie-title">.*</a>'|sed 's/<span.*<\/span>//g'|awk -F\> '{print $2}'|awk -F\< '{print $1}'|head -n 40 > ${TTMP} 
cat ${HTMP} |grep -E 'class="browse-movie-title">.*</a>'|awk -F\" '{print $2}'|head -n 40 > ${LTMP} 
if [ -s "${TTMP}" ]; then
    break
fi
done

}
getlink
while true
do
clear
logo
cat ${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
read -e -r -p "    Select Resource ID or Search:" input
echo -ne "\033[0m"
NUM=$(cat ${TTMP}|wc -l)
if [[ $input =~ ^-?[0-9]+$ ]] && (( $input > 0 && $input <= $NUM )); then
    HS=$input
    LINK=$(sed -n "${input}p" "${LTMP}")
    while :;
    do
    curl ${PXY} -s ${LINK}|grep -oE 'magnet:.*" class'|awk -F\" '{print $1}'|grep -E "720p|1080p|2160p" > ${MLTMP}
    if [ $? == 0 ];then
        break
    fi
    sleep 1
    done
    cat ${MLTMP}|grep -oE '720p|1080p|2160p'|nl
    NUM=$(cat ${MLTMP}|wc -l)
    while :;
    do
    echo -ne "\033[96;40m     Select Maglink ID:\033[0m"
    read -r input
    if [[ $input =~ ^-?[0-9]+$ ]] && (( $input > 0 && $input <= $NUM )); then
        xclip -selection clipboard <(sed -n "${input}p" "${MLTMP}") &> /dev/null
        echo -ne "\033[93;40m     Magnet Link Already Copy to Clipboard\033[0m"
        sleep 1 
	break
    elif [[ -z $input ]]; then
	break
    else
	continue
    fi
    done
elif [[ -z "$input" ]]; then
    continue
else
    HS=""
    KW=$input
    getlink
    continue
fi
done