#!/bin/bash
# source: http://forum.nasaspaceflight.com/index.php?topic=19846.990
# Modified by clavisound: automatic naming, url from cli and save to current folder, preview with mplayer
saveto=`pwd`
httpurl=$1
MPLAYER=`which mplayer`

if [ "$1" == '' ]; then
	echo "Usage: $0 http://whatafacka/wifi.m3u"
	echo
	echo "You can try $0 http://ebu_ios-i.akamaihd.net/hls/live/214400/ert/wifi.m3u8"
	exit 1
fi

# To name the saved stream get the host
programhost=`echo $httpurl | sed -e 's+http://++' -e 's+/.*++'`

# Now get the program
programfile=`echo $httpurl | sed -e 's+http://++'`
programfile2=`dirname $programfile | sed -e 's+.*/++'`
program=$programhost--$programfile2
filename="$saveto/$program--`date +%y%m%d-%s`"

trap "break; echo Finished recording. ; exit 0" SIGINT SIGTERM

bash -c "echo; echo \"Will start preview with mplayer in 8 seconds\"; sleep 8; mplayer -quiet $filename.ts" &

echo -n Buffering
#Get initial set of files
for nextfile in $(curl -s $httpurl | grep '.ts'); do
        echo -n .
        curl -s "$nextfile" >> $filename.ts
        lastfile="$nextfile"
done

echo 100\%

echo Starting continuous recording. Press CTRL-C to quit.
while true; do
        nextfile=$(curl -s $httpurl | grep '.ts' | tail -1)
        if [ "$nextfile" != "$lastfile" ]; then
                curl -s "$nextfile" >> $filename.ts
                lastfile="$nextfile"
        fi
 #File list updates every 10 seconds, but don't want to sleep too long and miss an update!
        sleep 7
done
