#!/bin/bash
#07/28/02
#stripstreams.sh
#copies definable mp3 streams from shoutcast into playlist

#expects following genrelist.txt format:
#playlistfiletouse.m3u,minbitrate(use127ifyouwant128kb/etc),numberofpagesfromshoutcast(20searches/page, limited by bitrate),searchstringonshoutcast

#i.e. - here's the grenrelist.txt that I'm using (has to be in the workdir as defined in the script)

#hiphop.m3u,80,2,http://www.shoutcast.com/directory/index.phtml?sgenre=Rap
#techno.m3u,100,2,http://www.shoutcast.com/directory/index.phtml?sgenre=Techno
#toplist.m3u,80,5,http://www.shoutcast.com/directory/index.phtml?sgenre=TopTen
#dance.m3u,80,2,http://www.shoutcast.com/directory/index.phtml?sgenre=Dance

echo "Start - `date`"
workdir="h:/audio/Playlists/shoutcast"
genrelist=genrelist.txt
tmphttpplaylist=${workdir}/workfiles/httpplaylist.htm

cd $workdir
if [ -d workfiles ]; then 
  echo "ERROR - last process has not exited yet -" 
  echo " delete ${workdir}/workfiles manually"
else
#start

mkdir workfiles

for genre in `cat ${workdir}/${genrelist}`;
do
 #get values
 playlist_final=`echo "$genre" | cut -f1 -d","` 
 min_quality=`echo "$genre" | cut -f2 -d","`
 max_pages_to_get=`echo "$genre" | cut -f3 -d","`
 httpstream=`echo "$genre" | cut -f4 -d","`

cd workfiles

#start work

#get pages

pagenumb=0

while [ "$pagenumb" -lt "$max_pages_to_get" ];
do 

newhttpstream="$httpstream&startat=`expr $pagenumb \* 20`"
#echo "start:${newhttpstream}:end"

let pagenumb=pagenumb+1
lynx -width=200 --dump $newhttpstream > warradio.txt
if [ `grep -c "Page . of ." warradio.txt`  -ne "0" ]; then


grep shoutcast-playlist warradio.txt > warradio.pls

#initialize pls file if on page1

if [ $pagenumb = 1 ]; then
 echo "#EXTM3U" > ${workdir}/${playlist_final}
fi


#not perfect; wont work if not expected format
linknumbs=`cat warradio.pls | awk "{ print $1 }" | cut -f1 -d"." `


for linknumb in `echo $linknumbs`;
  do
  #echo -n "D${linknumb}D "
  streamquality=`grep -A3 -B3 "\[${linknumb}]" warradio.txt | sed -e '1,/[${linknumb}()]/d' | \
    sed -e 1d | grep -v "\[tunein.gif]" | awk '{print  $NF }' | tail -1`
#  echo $streamquality
  if [ "$streamquality" -gt "$min_quality" ] 2> /dev/null ; then
 
    httpplaylist=`grep "${linknumb}\." warradio.txt | grep "http:" | cut -f2- -d"." ` 
    
    #get first playlist/parse
  
    wget -T2 -q  -O $tmphttpplaylist $httpplaylist
    this_title=`grep "Title1=" $tmphttpplaylist | cut -f2 -d")" | cut -b2- | sed -e 's/[/\`!-]//g'`
 #   echo "Test: $this_title"
  
    if [ `grep -c "$this_title" ${workdir}/${playlist_final}` -eq "0" ]; then
      echo -n "#EXTINF:-1," >> ${workdir}/${playlist_final}
      echo "${this_title}" >> ${workdir}/${playlist_final}
      grep "File1=" $tmphttpplaylist | cut -f2 -d"=" >> ${workdir}/${playlist_final}
    fi

   fi
done

fi


done

cd $workdir

done
rm -rf workfiles
echo "End - `date`"
fi
