#!/bin/ksh
# you need curl, yt-dlp

#usage
# $ sh yt-improved search query
#returns 5 urls for "search query".
#every time. You can use the same/your favorite
#instance by changing the 'ins' variable. See
#example below.

#ins=$(curl -s "https://triapul.cz/files/farside/invidious.txt" | sort -R | sed 1q)
ins=https://invidious.nerdvpn.de

help() {
cat <<eof
usage: ksh yt <search query>

After making a search and
outputting results, choose
a number immediately followed
by an option.

d - download video

r - rip audio

c - copy url to ~/url

e - echo url

for example: 

3r will rip audio
from the third video.

5e will echo the url of
the fifth video in STDOUT.

eof
}

if [[ $1 = '-h' ]]; then
help;
return 0
fi

query=$*
results=5

query=$(echo $query | sed 's/ /+/g')
curl -s "$ins/search?q=$query" | grep -e "p dir" | head -n$results > ~/.yt-tmp
x=1
while read line; do
 url[$x]=$(print "https://youtube.com$(print "$line" | cut -d\" -f2)")
 print "$x) $line" | sed -e 's/<[^>]*>//g'
((x++))
done < ~/.yt-tmp 
#rm ~/.yt-tmp
print
print "[1-5][rdce])"
print "ie: 1r - rips audio from video 1"

read var
x=$(print $var | rev | tail -c2)

case $var in
*r) yt-dlp -x --audio-format mp3 "${url[$x]};;
*d) yt-dlp -f w "${url[$x]};;
*c) print ${url[$x]} > ~/url;;
*e) echo "${url[$x]}";;
esac
