#!/bin/bash

# only one parameter is used: res tim in minutes
if [ $# -lt 1 ] ; then
 echo no arguments, recording one hour
 rectime=60
else
rectime=$1
fi

retrycounter=0

let rectime=rectime*60
echo recording $rectime seconds

mydate=`date +"%Y%m%d-%R"`
echo rec start: $mydate

while [  \""$kpid"\" = \"\" ] ; do

wget -q http://62.153.249.30/live_dlf -O "dlf_$mydate.mp3" &

sleep 1

kpid=`pgrep -f  dlf_${mydate}.mp3`


if [ \""$kpid"\" = \"\" ] ; then
       echo still empty pid, retrying wget
fi

sleep 9

let retrycounter=retrycounter+10

if [ $retrycounter -gt $rectime ] ; then

   echo "giving up !"
   exit 1
fi

done


# now a wget is running
# no use to record beyond the original stop time if it was difficult to
# start the wget
let rectime=rectime-retrycounter+10

echo "PID of wget: $kpid"
sleep $rectime
kill $kpid

# the following was an earlier fall back which I dont need anymore
if [ \""$kpid"\" = \"\" ] ; then
       echo pid still unknown, killing all wgets, hope thats ok
#       killall wget
fi
