#!/bin/bash
# apk add termux-exec bash
set -e


# settings:
#   write youtube-dl to /home/(You)/bin/youtube-dl,
#   write downloaded vids to the current folder
bindir=~/bin
outdir="$(pwd)"


# detect if we're on android,
[ -e /storage/emulated/0/ ] &&
	android=y ||
	android=


# if android: overwrite all the paths above
[ $android ] &&
{
	outdir="/storage/emulated/0/Movies"
	bindir="$outdir"
	mkdir -p "$outdir"
	android=1
} ||
	android=0


# derived config
ytdl="$bindir/youtube-dl"

cd -- "$outdir"


msg() { printf '\033[1;30m>\033[0;34m>\033[1m>\033[0m %s\n' "$1" >&2; }
inf() { printf '\n\033[1;30m>\033[0;32m>\033[1m>\033[0;32m %s\033[0m\n' "$1" >&2; }
wrn() { printf '\n\033[1;30m>\033[0;33m>\033[1m>\033[0;33m %s\033[0m\n' "$1" >&2; }
err() { printf '\n\033[1;30m>\033[0;31m>\033[1m>\033[0;31m %s\033[0m\n' "$1" >&2; }
ask() { printf '\033[1;30m>\033[0;35m>\033[1m>\033[0;35m %s\033[0m' "$1" >&2; IFS= read -u1 -r r; }
out() { printf '    %s\n' "$1" >&2; }
die() { err "$1"; exit 1; }

command -v wget >/dev/null && dlcmd="wget -qO-" ||
command -v curl >/dev/null && dlcmd="curl -L" ||
{
	[ $android ] &&
		pkg install -y wget ||
		die "need either wget or curl to continue"
}


command -v python3 >/dev/null ||
{
	[ $android ] &&
		pkg install -y python3 ||
		die "need python3 to continue"
}


http_get()
{
	command -v wget >/dev/null &&
	{
		wget -qO- "$1"
		return $?
	}
	curl -L "$1"
}


[ -e "$ytdl" ] ||
{
	msg "do not have youtube-dl yet"
	ver="$(http_get https://yt-dl.org/update/LATEST_VERSION)"
	msg "downloading version $ver"
	http_get "https://yt-dl.org/downloads/$ver/youtube-dl" > "$ytdl"
}


inf "ready to download stuff! choose an option below:"
out
msg "to check for yt-dl updates:"
out "press U followed by Enter"
out
msg "to download an entire video+audio:"
out "paste the URL and hit Enter"
out
msg "to download just audio (or to choose video quality):"
out "press F, then space, then paste URL and hit Enter"
out

ask

re="^ *[uU] *$"
[[ "$r" =~ $re ]] &&
{
	msg "checking for updates..."
	python3 "$ytdl" -U
	exit $?
}

re="^ *[fF] +..."
[[ "$r" =~ $re ]] &&
{
	url="${r:2}"
	msg "checking available formats..."
	python3 "$ytdl" -F "$url"
	msg "choose formats, one or more, separated by +"
	ask
	msg "downloading formats [$r]..."
	python3 "$ytdl" -f "$r" "$url"
	exit $?
}

msg "downloading [$r]..."
python3 "$ytdl" "$r"

