#!/bin/sh

# ardget 0.1
# by Hanno Boeck, http://www.hboeck.de/

# latest version is available at http://www.int21.de/ardget/

# I, the copyright holder of this work, hereby release it into the public domain. This applies worldwide.
# In case this is not legally possible:
# I grant anyone the right to use this work for any purpose, without any conditions, unless such conditions
# are required by law.

if [ "$1" = "" ]; then
	echo "Usage: `basename $0` [url]"
	exit
fi

if type flvstreamer > /dev/null 2>&1; then
	echo "Using flvstreamer"
	tool="flvstreamer"
elif type rtmpdump > /dev/null 2>&1; then
	echo "Using rtmpdump"
	tool="rtmpdump"
else
	echo "ERROR: Needs flvstreamer or rtmpget"
	echo "http://savannah.nongnu.org/projects/flvstreamer/"
	echo "http://rtmpdump.mplayerhq.hu/"
	exit
fi

httpurl=`echo $1 | sed -e 's:^.*\(http[#:/\.?=&_a-zA-Z0-9]*\).*:\1:g'`

echo HTTP URL is $httpurl

webpage=`wget -q -O - $httpurl`
rtmpurl=`echo $webpage | grep -o 'rtmp[:/\.=_a-zA-Z0-9]*' | tail -n 1`
filename=`echo $webpage | grep -o '<title>.*</title>' | sed -e 's:.*>\(.*\)<.*:\1:g' -e 's:[^a-zA-Z0-9\. ]::g' -e 's:  : :g' -e 's: :_:g'`.flv

echo RTMP URL is $rtmpurl

host=`echo $rtmpurl | sed -e 's!rtmp://\([\.a-zA-Z0-9]*\).*!\1!g'`
app=`echo $rtmpurl | sed -e 's!rtmp://[\.a-zA-Z0-9]*/\([\.a-zA-Z0-9]*\).*!\1!g'`
playpath=`echo $rtmpurl | sed -e 's!rtmp://[\.a-zA-Z0-9]*/[\.a-zA-Z0-9]*/\(.*\)!\1!g'`
#filename=`echo $playpath | sed -e 's![:/]!_!g' -e 's:f4v:flv:g'`

echo Host is $host, app is $app, playpath is $playpath
echo Saving as $filename

flvstreamer -n $host -a $app -y $playpath -o $filename
