# A Makefile to download episodes of the German TV show Tatort.
# Author: Marc Mezzarobba, 2014.
# Public domain.

base_url = http://www.ardmediathek.de

SHELLOPTS = errexit
.DELETE_ON_ERROR:
.ONESHELL: # but keep the \ for now for compatibility with older make versions
.PHONY: all_available feed.rss
.SECONDARY:
.SUFFIXES:

all_available: feed.rss
	@ < $< xmlstarlet sel -t \
	    -m '//item[contains(title, "tgl. ab 20") and not(contains(title, "Hörfassung"))]' \
	    -v 'substring-before(substring-after(link, "?documentId="), "&")' \
	    -o ' "' -v 'title' -o '"' -n \
	| while read docid title; do \
		if [ -n "$${docid}" ]; then \
			echo == $$title ==; \
			echo $${title} > $${docid}.title; \
			${MAKE} $${docid}.ok; \
		fi \
	done

feed.rss:
	curl -s -S "${base_url}/tv/Tatort/Sendung?documentId=602916&rss=true" > "$@"

%.json:
	curl -s -S "${base_url}/play/media/$*" > "$@"
	test -s "$@"

%.mp4: %.json
	stream_url=$$(<"$*.json" jq -r '[._mediaArray[] | ._mediaStreamArray[] | select(.flashUrl | not)] | max_by(.quality) | ._stream'); \
	curl -s -S "$${stream_url}" > "$@"

%.ttaf: %.json
	subtitles_rel_url=$$(<"$*.json" jq -r '._subtitleUrl'); \
	curl -fsS -o "$@" "${base_url}$${subtitles_rel_url}" && [ -s "$@" ] \
	|| curl -fsS -o "$@" "http://mediathek.daserste.de/static/avportal/untertitel_mediathek/$*.xml" \
	|| curl -fsS -o "$@" "http://mediathek.daserste.de/static/avportal/untertitel_mediathek_preview/$*.xml"

%.srt: %.ttaf
	-ttaf2srt.py $< > "$@"

%.ok: %.srt %.mp4
	touch $@

# vim: tw=140
