#!/bin/bash

url=$1
fileout=$2
lang=$3

fileouttmp="rtmpdump_output_$(date +%Y%m%d-%H%M%S-%N)"


if [ "$url" = "-h" ]; then
        echo "usage: '$0 URL OUTFILE [lang]'"
        echo ""
        echo "URL: Path to arte+7 video page"
        echo "OUTFILE: Filename to store Video. '.mp4' added automatically."
        echo "optional: lang = 'fr' for french version, download in german by default. "
        exit 0
fi

if [ "$fileout" = "" ]; then
        echo "Two arguments required! Output filename is missing."
        exit 0
fi

if [ "$lang" = "fr" ]; then
        echo "Downloading French Version ..."
else
        echo "Downloading German Version ..."
        lang="de"
fi

langcode1='<video lang="'
langcode3='"'
langcode=$langcode1$lang$langcode3
#echo "${langcode}"

echo "Downloading" $url "to" $fileout " ..."
wget -q $url -O - | grep '<embed src="http' | sed -n -e 's|.*videorefFileUrl=\(.*\)".*|\1|p' | sed -e 's/%2C/,/gi;s/%3A/:/gi;s/%25/%/gi;s/%20/ /gi;s/%09/ /gi;s/%21/!/gi;s/%22/"/gi;s/%23/#/gi;s/%24/\$/gi;s/%26/\&/gi;s/%27/'\''/gi;s/%28/(/gi;s/%29/)/gi;s/%2A/\*/gi;s/%2B/+/gi;s/%2D/-/gi;s/%2E/\./gi;s/%2F/\//gi;s/%3B/;/gi;s/%3D/=/gi;s/%3E//gi;s/%3F/?/gi;s/%40/@/gi;s/%5C/\\/gi;s/%5E/\^/gi;s/%5F/_/gi;s/%7E/~/gi;' | xargs wget -q -O - | grep "${langcode}" | sed -n -e 's|.*ref="\(.*\)" />|\1|p' | xargs wget -q -O - | grep '<url quality="hd">' | sed -n -e 's|<url quality="hd">\(.*\)<\/url>|\1|p' | xargs -I {} rtmpdump -r {} -o $fileouttmp

mv $fileouttmp "$fileout.mp4"
