#!/bin/bash

# ffmpeg to merge files (as used by yt-dl):
#  ffmpeg -y -i video.webm -i audio.webm -c copy -map 0:v:0 -map 1:a:0 merged.temp.webm
# to force max height to 1080:
#  youtube-dl --no-playlist -f "bestvideo[height<=?1080]+bestaudio/best" "$ptturl"
#
PTT_DESTDIR=./
#PTT_FORMAT='-f "bestvideo[height<=?1080]+bestaudio/best"'
PTT_FORMAT=
PTT_KEEP=
PTT_PLAYLIST="--no-playlist"

PTT_CONFIGFILE=~/.config/ptt.d/pttyt.conf
if [ ! -f $PTT_CONFIGFILE ]; then
	PTT_CONFIGFILE=/etc/ptt.d/pttyt.conf
fi

pttyt_exit()
{
	printf "\e]2;`basename $SHELL`\7"
	exit 0;
}

printf "\e]2;`pwd`\7"

while true; do
	if [ "x$1" == "x" ]; then
		read ptturl
	else
		ptturl=$1
	fi
	if [ -f $PTT_CONFIGFILE ]; then
		. $PTT_CONFIGFILE
	fi
	pttfmt=`echo $ptturl | grep ";" | cut -d";" -f2`
	pttout=""
	if [ "x$pttfmt" != "x" ]; then
		ptturl=`echo $ptturl | cut -d";" -f1`
		pttfcd=`echo $pttfmt | cut -d" " -f2`
		pttout="-o %(title)s-%(id)s.$pttfcd.%(ext)s"
		PTT_FORMAT=$pttfmt
	fi
	if [ "x$ptturl" == "xpwd" ]; then
		echo " --> Working dir: `pwd`"
		continue
	fi
	if [ "x$ptturl" == "xr" ]; then
		ptturl=$pttoldurl
	fi
	if [ "x$ptturl" == "x" -o "x$ptturl" == "xq" ]; then
		pttyt_exit
	fi
	pttoldurl=$ptturl
	ptturl_http=`echo "$ptturl" | grep "/"`
	if [ "x$ptturl_http" == "x" ]; then
		ptturl="https://www.youtube.com/watch?v="$ptturl;
	fi
	echo " --> $ptturl ($PTT_FORMAT)"
	echo " Saving to $PTT_DESTDIR"
	yt-dlp -u $PTT_USER -p $PTT_PWD \
		-P "$PTT_DESTDIR" \
		$PTT_KEEP $PTT_PLAYLIST $PTT_FORMAT \
		$pttout "$ptturl" || \
		(echo ' (retrying whit -f 18)' && yt-dlp -u $PTT_USER -p $PTT_PWD \
		-P "$PTT_DESTDIR" \
		$PTT_KEEP $PTT_PLAYLIST "-f 18" \
		$pttout "$ptturl" )
	if [ "x$1" != "x" ]; then
		pttyt_exit
	fi
done

pttyt_exit

