#!/bin/sh

set -e

argv0="$0"

PIGPEN="$(pig_pen)"

latin(){
	case "$1" in
	*json)	jq '.feed.pig' <"$1" ;;
	*xml)	xq '.feed.pig' <"$1" ;;
	esac
}

list_channels(){
	pscat \
		[ sh -c "for file in \"$PIGPEN\"/*.xml; \
			do xq '{(.feed.link[0].\"@href\"): .feed.title}' \"\$file\"; \
			done 2>/dev/null" ] \
		[ sh -c "for file in \"$PIGPEN\"/*.json; \
			do jq '{(.feed.link[0].\"@href\"): .feed.title}' \"\$file\"; \
			done 2>/dev/null" ] \
		[ printf "\n" ] \
		| sed \
			-e '/{/d' \
			-e '/}/d' \
			-e 's/^  \"//g' \
			-e 's/\": \"/	/g' \
			-e 's/\,$//g' \
			-e 's/\"$//g'
}

list_videos(){
	file="$(printf "$PIGPEN"/$( \
		list_channels \
			| sed "/$1/q" \
			| tail -n 1 \
			| cut -f 1 \
			| xargs pig_name \
	)*)"
	case "$file" in
	*json)
		jq \
			'reduce .feed.entry[] as $item (
				{};
				. + { ($item.link."@href"): $item.title }
			)' "$file"
		;;
	*xml)
		xq \
			'reduce .feed.entry[] as $item (
				{};
				. + { ($item.link."@href"): $item.title }
			)' "$file"
		;;
	*)
		printf "No file found!\n" 1>&2
		true
		;;
	esac | sed \
		-e '1d' \
		-e '$d' \
		-e 's/\": \"/	/g' \
		-e 's/^  \"//g' \
		-e 's/\,$//g' \
		-e 's/\"$//g' # this is really hacky

}

stow(){
	name="$PIGPEN/$(pig_name "$1")"
	pig_fetch "$1" | xq "$(
			date '+%Y-%m-%dT%T' \
			| xargs printf '
			. * { feed: { pig: {
				feed_url: "%b",
				pet_sound: "choo",
				stow_date: "%b",
				version: "0"
			} } }' "$1" \
		)" >"$name.json"
	rm -f "$name.xml"
}

watch(){
	youtube-dl -F "$1"
	printf "Pick a format [22]: "
	input="$(head -n 1 | tr -d '\n')"
	str isalnum "$input" \
		&& str isdigit $input \
		|| input=22 \
		&& youtube-dl -f $input "$1" -o - \
			| mpv -
}

usage(){
	printf "\
Usage: %s
	list_channels
	list_videos [channel name]
	listen [video URL]
	refresh (channel name...)
	subscribe [channel URL...]
	watch [video URL]
	watch_latest [channel name]
" "$argv0" 1>&2
}

case "$1" in
list_channels)
	! str isvalue "$2" \
		|| usage
	list_channels
	;;
list_videos) # do something with youtube-dl?
	list_videos "$2"
	;;
listen)
	str isvalue "$2" \
		|| usage
	while str isvalue "$2"
		do youtube-dl "$2" -f bestaudio -o - \
			| mpv -
		shift
	done
	;;
refresh)
	if ! str isvalue "$2"
		then for file in "$PIGPEN"/*
			do stow "$( \
				latin "$file" \
					| jq -r '.feed_url' \
			)"
		done
	else
		while str isvalue "$2"
			do stow "$( \
				latin "$( \
					list_channels \
						| grep "$2" \
						| cut -f 2 \
				)" | jq '.feed_url' \
			)"
			shift
		done
	fi
	;;
subscribe)
	str isvalue "$2" \
		|| usage
	while str isvalue "$2"
		do stow "http://www.youtube.com/feeds/videos.xml?channel_id=$(
				youtube-dl \
					--get-filename \
					--playlist-items 1 \
					-o '%(channel_id)s' \
					"$2" \
		)"
		shift
	done
	;;
watch) # needs work
	str isvalue "$2" \
		|| usage
	while str isvalue "$2"
		do watch "$2"
	done
	;;
watch_latest)
	str isvalue "$2" \
		|| usage
	watch "$( \
		list_videos "$2" \
			| head -n 1 \
			| cut -f 1 \
	)"
	;;
*)	usage ;;
esac

exit 0
