#!/bin/sh

#QUERY_STRING=155

if [ -f /usr/local/etc/xspf.conf ]; then
  . /usr/local/etc/xspf.conf
fi

WGET=${WGET:-/usr/bin/wget}

CACHEPATH=${CACHEPATH:-/opt/tmp}
TEMP=${TEMP:-/tmp}
STORAGEPATH=${STORAGEPATH:-/tmp}

print_item()
{
    value=`sed -e "s/.*$1: <\/font><\/td><td><font class=default><b>//" $INFOFILE | sed 's/<\/b>.*//'`
    value=`echo "$value" | sed -e 's/<.*>//g;s/&amp;/&/g;s/&nbsp;/ /g;s/&lt;/</g;s/&gt;/>/g'`
    echo "<item><name>$1:</name><value>$value</value></item>"
    return 0
}

print_warning()
{
    echo "Content-type: text/plain"
    echo
    echo "WARNING! $1"
}

if [ ! -f $WGET -o ! -x $WGET ]; then
    print_warning "'$WGET' not found"
    exit
fi

if [ ! -d $TEMP ]; then
    print_warning "'$TEMP' not found"
    exit
fi

[ ! -d $CACHEPATH ] && CACHEPATH=$TEMP

id=`echo "$QUERY_STRING" | awk -F, '{print $1}'`
cmd=`echo "$QUERY_STRING" | awk -F, '{print $2}'`

TMPFILE=$TEMP/tmp.$$
INFOFILE=$CACHEPATH/shoutcast.$id.info
PLSFILE=$CACHEPATH/shoutcast.$id.pls
TUNEINDAT=$STORAGEPATH/shoutcast.tuneinbase.dat

USERAGENT="Mozilla/4.0 (compatible; MSIE 6.0)"

if [ -f $TUNEINDAT ]; then
    TUNEINBASE="`sed -ne '1p' $TUNEINDAT`"
fi

if [ -z "$TUNEINBASE" ]; then
    TUNEINBASE="/sbin/tunein-station.pls"
fi

$WGET -q -O $TMPFILE "http://www.shoutcast.com:80$TUNEINBASE?id=$id" 2>/dev/null
if [ -f $TMPFILE ]; then
    cp $TMPFILE $PLSFILE
fi
rm -f $TMPFILE

if [ ! -f $PLSFILE ]; then
    echo "Connection: close"
    echo
    exit
fi


numberofentries=`sed -ne '/^numberofentries=/p' $PLSFILE | awk -F= '{print $2}'`

streamurl=
tit=dummy
index=0
while [ -n "$tit" ]; do
    let index=$index+1
    tit=`sed -ne "/^Title$index=\(.*- 0\/[0-9]*\)/p" $PLSFILE`
done
streamurl=`sed -ne "/^File$index=/p" $PLSFILE | sed -e "s/^File$index=//"`
if [ -z "$streamurl" ]; then
    let index=$index-1
    streamurl=`sed -ne "/File$index=/p" $PLSFILE | sed -e "s/File$index=//"`
fi

shoutcasturl=
index=0
while [ -z "$shoutcasturl" -a $index -lt $numberofentries ]; do
    let index=$index+1
    shoutcasturl=`sed -ne "/^File$index=/p" $PLSFILE | sed -e "s/^File$index=//" | sed -ne '/^http:\/\/[0-9a-zA-Z\.:]*\/*$/p'"`
done


if [ -n "$shoutcasturl" ]; then

  $WGET -q --header "User-Agent: $USERAGENT" -O $TMPFILE "${shoutcasturl}" 2>/dev/null
  
  if [ -f $TMPFILE ]; then
    cp $TMPFILE $INFOFILE
  fi
  rm -f $TMPFILE
  
fi  

if [ -f $INFOFILE ]; then
  type=audio/`cat $INFOFILE | sed -e 's/.*audio\///' | sed 's/<.*//'`
  
  case $cmd in
    stream)
      echo "Content-type: $type"
      echo
      exec $WGET -q -O - "$streamurl" 2>/dev/null
    ;;
    *)
      echo "Content-type: text/xml"
      echo
      echo "<?xml version='1.0' encoding='UTF-8'?>"
      echo "<info>"
      echo "<stream href='$streamurl'/>"
  	  print_item 'Current Song'
  	  print_item 'Stream Status'
  	  print_item 'Average Listen Time'
  	  print_item 'Stream Title'
  	  print_item 'Content Type'
  	  print_item 'Stream Genre'
      echo "</info>"
    ;;
  esac
fi
