#!/bin/sh
#author:Wos
#nyaa Terminal
#default sort by seeder
HTMP="/tmp/nyaa.html"
TTMP="/tmp/nyaa_title.txt"
SZTMP="/tmp/nyaa_size.txt"
LTMP="/tmp/nyaa_maglink.txt"
HS=""
DOMAIN="https://nyaa.si/"
PXY="-x http://127.0.0.1:7891"
function modeselect(){
     echo "1:Anime"
     echo "2:AV"
     echo -n "Choose Mode:"
     read -r input
     if [ $input == 2 ]; then
         DOMAIN="https://sukebei.nyaa.si/"
     fi
}
function logo()
{
    echo -e "\033[96;40m"
    base64 -d <<<"H4sIAAAAAAAAA51QQQrDMAy75xW6ZYVBPxRQH+LHT7LdDrae6mA5FopECwJw/xddd/zPNgILgWgn
vbmwuMjlAvWLW95Lp7fywAr02cHjRGmKUciktJM4vFk5zbbOHrFSbUdlfDFZh+0ecXNKJw/NxVjk
G4lstEfeaUllVLNn6Rij/4w+W3nPanwAaCZzvpgBAAA="|gunzip
    echo "${DOMAIN}"|awk -F\/ '{print "     Current Mode:"$3}'
    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=$@
COOKIE="__ddg1_=6q2Oet3Q7On3ZzY1YEIN"
function getlink(){
while :;
do
curl ${PXY} --cookie "${COOKIE}" -s ${DOMAIN%%/}"/?f=0&c=0_0&q="${KW// /+}"&s=seeders&o=desc" > ${HTMP}
cat ${HTMP} |grep -oE '/view/[0-9]+" title=".*">'|awk -F\" '{print $3}'|head -n 40 > ${TTMP} 
cat ${HTMP} |grep -E 'GiB|MiB'|awk -F\> '{print $2}'|awk -F\< '{print $1}'|head -n 40 > ${SZTMP}
cat ${HTMP} |grep -oE 'href="magnet:.*"'|awk -F\" '{print $2}'|head -n 40 > ${LTMP} 
if [ -s "${TTMP}" ]; then
    break
fi
done

}
modeselect
getlink
while true
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
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 -ne "\033[93;40m    Magnet Link Already Copy to Clipboard\033[0m"
    sleep 1 
elif [[ -z "$input" ]]; then
    continue
else
    HS=""
    KW=$input
    getlink
    continue
fi
done