#!/bin/bash
#author:Wos
#YuTube Music Terminal
HTMP="/tmp/ymusic.html"
TTMP="/tmp/ymusic_title.txt"
LTMP="/tmp/ymusic_link.txt"
DOMAIN="https://iv.ggtyler.dev/"
#scrape proxy
PXY="-x http://127.0.0.1:7891"
#mpv proxy
PPXY="--http-proxy=http://127.0.0.1:7891"
function logo()
{
    echo -e "\033[96;40m"
    base64 -d <<<"H4sIAAAAAAAAA5VRwQ2EMAz7dwr/AOmkLoRkBsnw58StBLrrgwaoYzsGVGC5+AMW+uhaMczKi5g9
ufMwEwhrNk2n9MIoQqYWcG3EJd/prkvXPjY9e2oy8enckpV2YWRx5o1SfzJNoXf7uwKVF0D8qd0J
Lcc+zvOdPUM/0QuLTEuhxDcnnxPKqrH1AbxY7QvKXr5/yAEAAA=="|gunzip
    echo -e "\033[0m"
}

function usage(){
   logo
   echo  "usage:`basename $0` [keyword]"
   echo ""
   exit -1
}
if [ $# == 1 ] && [ $1 == "-h" ];then
   usage
fi
KW=$@ 
PG=1
function getlink(){
while :;
do
curl ${PXY} -s ${DOMAIN%%/}"/search?q=music+"${KW// /+}"&page="${PG} > ${HTMP} 
if [ $? == 0 ]; then
    break
fi
sleep 1
done
cat ${HTMP} |grep -E '<a href="/watch'|awk -F\> '{print $3}'|awk -F\< '{print $1}' > ${TTMP} 
cat ${HTMP} |grep -E '<a href="/watch'|awk -F\" '{print $2}'|awk -F\= '{print $2}' > ${LTMP} 
}
getlink
while :; 
do
clear
logo
paste -d' ' ${SZTMP} ${TTMP}|sed "s/&#39;/\'/g"|nl
echo -e "\033[96;40m"
echo -e "    [^c:Exit,-1:Pre Page,Enter:Next Page]"
echo -n "    Select Resource ID or Search:"
echo -ne "\033[0m"
read -r input
echo -ne "\033[?25l"
NUM=$(cat ${TTMP}|wc -l)
if [[ $input =~ ^-?[0-9]+$ ]] && (( $input > 0 && $input <= $NUM )); then
    #tag 251 140
    while :;
    do
    LINK=${DOMAIN%%/}"/latest_version?id="$(sed -n "${input}p" "${LTMP}")"&itag=251"
    LINK2=${DOMAIN%%/}"/latest_version?id="$(sed -n "${input}p" "${LTMP}")"&itag=140"
    curl ${PXY} -s -i "${LINK}" > ${HTMP}
    PLINK=$(cat ${HTMP}|grep location|awk '{print $2}')
    echo -e "\033[93;40m"
    echo -e "    Play Link Already Sync to Clipboard"
    echo -e "    ( m:🔇 9:🔈︎ 0:🔊 q:⏹  space:⏯︎  up:⏩)\033[0m"
    if [[ $PLINK =~ ^(https://).* ]]; then
	echo "${PLINK}"|xclip -selection clipboard
	while :;
	do
        mpv ${PPXY} --really-quiet --vid=no "${PLINK}" 
	    if [ $? == 0 ]; then
	        break
	    fi
	    sleep 1
        done
	echo -ne "\033[?25h"
	break
    else
        curl ${PXY} -s -i "${LINK2}" > ${HTMP}
        PLINK=$(cat ${HTMP}|grep location|awk '{print $2}')
	echo "${PLINK}"|xclip -selection clipboard
	while :;
	do
        mpv ${PPXY} --really-quiet --vid=no "${PLINK}" 
	    if [ $? == 0 ]; then
	        break
	    fi
	    sleep 1
        done
	echo -ne "\033[?25h"
	break
    fi
    done
elif [[ -z "$input" ]]; then
    PG=$(($PG+1))
    getlink
    continue
elif [[ "$input" == "-1" ]]; then
    if [[ $PG > 1 ]]; then
        PG=$((($PG)-1))
    else
	PG=1
    fi
    getlink
    continue
else
    KW=$input
    getlink
    continue
fi
done