#!/bin/sh
# select bitreich tv dimensions and memecache memes.
# requirements: lots.

annna="$HOME/.cache/annna"
hashtags="${annna}/modules/hashtags/hashtags.txt"
dimensions="${annna}/dimensions.txt"
updatestr="update local memecache"
interludestr="watch Bitreich TV interlude"

TARDIS_MENU=${TARDIS_MENU:-"dmenu -l 10 -p ${0##*/}:"}
TARDIS_PLUMB=${TARDIS_PLUMB:-xdg-open}
TARDIS_VIDEO=${TARDIS_VIDEO:-mpv}

usage() {
	printf 'usage: %s [-cuU]\n' "${0##*/}" 1>&2
	exit 1
}

update() {
	cd "$annna" && git pull >/dev/null
	getdimensions
}

getdimensions() {
	printf '/tv\n' | nc bitreich.org 70 | grep -E '^9.*\.m3u' |\
		awk -F'	' '{printf("gopher://%s:%d/%c%s\n", $3, $4, $1, $2)}' \
		> "$dimensions"
}

init() {
	if ! test -r "$hashtags"; then
		if ! test -d "$(dirname "$annna")"; then
			mkdir -p "$(dirname "$annna")"
		fi
		cd "$(dirname "$annna")"
		git clone git://bitreich.org/annna
	fi
	if ! test -r "$dimensions"; then
		getdimensions
	fi
}

init
clip=""
while getopts uUc arg; do
	case ${arg} in
		u) update; exit 0 ;;
		U) update ;;
		c) clip=1 ;;
		*) usage ;;
	esac
done
shift $((OPTIND - 1))
if test $# != 0; then
	usage
fi

meme="$( (printf '%s\n%s\n' "$updatestr" "$interludestr"; \
	cat "$dimensions" "$hashtags") | ${TARDIS_MENU})"
if test "$meme" = "$updatestr"; then
	update
elif test "$meme" = "$interludestr"; then
	${TARDIS_PLUMB} ssh://time-machine@bitreich.org
elif test "$meme"; then
	if printf '%s\n' "$meme" | grep -qE '\.m3u$'; then
		if test "$clip"; then
			printf '%s' "${meme}" | xclip -i
		fi
		${TARDIS_VIDEO} "$meme"
	else
		if test "$clip"; then
			printf '%s' "${meme% *}" | xclip -i
			printf '%s' "${meme#* }" | xclip -i -selection clipboard
		fi
		${TARDIS_PLUMB} "${meme#* }"
	fi
else
	exit 1
fi
