#!/bin/bash
#
# Arte+7 video downloader (french HD version)
# Author: Gerome Fournier 
# Version: 0.3
# Date: 2013-09-15
# http://foutaise.org/code/

usage()
{
	local progname=${0##*/}

	cat <<EOF
Dump French HD version of a arte+7 video
Usage:

    $progname <arte+7 url>

Example:

    $progname "http://www.arte.tv/guide/fr/047158-000/evasion-fiscale?autoplay=1" > evasion-fiscale.flv
EOF
}

if [ "$1" == "-h" ]; then
	usage
	exit 0
fi

if [ "$#" -ne 1 ]; then
	echo "Wrong number of arguments" >&2
	exit 1
fi

# walk through several URLs to find the stream
link1=$(curl -s "$1" \
	| grep ALL.json \
	| head -n1 \
	| sed -e 's/^.*arte_vp_url="//' -e 's/".*$//')
if [ -n "$link1" ]; then
	json_hd_french=$(curl -s "$link1" \
		| tr '{' '\n' \
		| grep '"quality":"HD - 720p".*"versionCode":"\(VF\|VF-STF\|VOF-STF\)"' \
		| tr ',' '\n')
	streamer=$(grep '^"streamer"' <<< "$json_hd_french" | cut -d: -f2- | tr -d '"')
	url=$(grep '^"url"' <<< "$json_hd_french" | cut -d: -f2- | tr -d '"')
	if [ "${streamer:0:7}" == "rtmp://" ]; then
		rtmpdump -r "$streamer" -y "mp4:$url"
		exit 0
	fi
fi

echo "Unable to find source stream" >&2
exit 1