#!/bin/sh
# 0.0.4 - GuestToo - Sep 4, 2005

# prefer xmms, otherwise use gxine:

PLAYER=`which xmms` || PLAYER=gxine
#PLAYER=gmplayer


# -----

APPDIR=`dirname "$0"`
cd "$APPDIR"
APPDIR="`pwd`"
MSG=`which gxmessage` || MSG=xmessage

if [ "$1" = "-uninstallwrapper" ]
then
  $MSG -center -title "Internet Radio" "still not implemented"
  exit
fi

if [ "$1" = "-usexmessage" ]
then
  cd "$APPDIR"
  ln -sf AppRun1 AppRun
  exec "$APPDIR/AppRun"
fi

if [ "$1" = "-usexdialog" ]
then
  cd "$APPDIR"
  ln -sf AppRun2 AppRun
  exec "$APPDIR/AppRun"
fi

# ----- create an Xdialog interface gui program:

FOO=/tmp/foo
# following line not necessary when the file is sourced
echo '#!/bin/sh' > $FOO
echo 'RETN=`Xdialog --clear --title "Internet Radio" --stdout --center --no-tags --menu "DoubleClick to Play Station" 0 0 0 \' >> $FOO
cat $APPDIR/stations.txt >> $FOO
echo '#`' >> $FOO
chmod a+x $FOO
. $FOO

[ $? -eq 0 ] || exit

URL=$RETN

# xmms probably needs the plugin
if echo $URL | grep 'rtsp://' > /dev/null
then
  exec gxine $URL
fi
if echo $URL | grep '\.ram$' > /dev/null
then
  exec gxine $URL
fi
if echo $URL | grep '\.mp3$' > /dev/null
then
  exec gxine $URL
fi

[ -d /tmp/radiotmp ] || mkdir /tmp/radiotmp
cd /tmp/radiotmp
rm -f /tmp/radiotmp/*

# pawedcast 1
if [ "$URL" = "http://www.murga.org/~puppy/download.php?id=633" ]
then
 cd /tmp
 rxvt -e wget --no-http-keep-alive -t 4 --waitretry=10 -c $URL -O pawed1.wav.zip
 unzip -t pawed1.wav.zip || exit 1
 cd /tmp/radiotmp
 unzip /tmp/pawed1.wav.zip
 PLAYLIST=pawed1.wav
 exec $PLAYER $PLAYLIST
fi

# pawedcast 2
if [ "$URL" = "http://www.murga.org/~puppy/download.php?id=648" ]
then
 cd /tmp
 rxvt -e wget --no-http-keep-alive -t 4 --waitretry=10 -c $URL -O raffy.zip
 unzip -t raffy.zip || exit 1
 cd /tmp/radiotmp
 unzip /tmp/raffy.zip
 PLAYLIST=raffy.wav
 exec $PLAYER $PLAYLIST
fi

# crude workaround ...
# xmms doesn't seem to play pls urls directly
# gxine sometimes needs the user-agent workaround
cd /tmp/radiotmp
if ! wget --no-http-keep-alive -t 4 --waitretry=10 -c --user-agent='WinAmp 5.0' $URL
then
  exit 1
fi
# crude workaround ...
# (there's probably a better way, i'm no scripting expert
# mv *.pls* *.pls doesn't work, this does)
cat *.pls* > radio.pls
cat *.m3u > radio.m3u
cat *.asx > radio.asx
cat *.ram* > radio.ram
cat *.rm* > radio.rm
cat *.rpm* > radio.rpm
PLAYLIST=
[ -s radio.rpm ] && PLAYLIST=radio.rpm
[ -s radio.rm ] && PLAYLIST=radio.rm
[ -s radio.ram ] && PLAYLIST=radio.ram
[ -s radio.asx ] && PLAYLIST=radio.asx
[ -s radio.m3u ] && PLAYLIST=radio.m3u
[ -s radio.pls ] && PLAYLIST=radio.pls
if grep 'numberofentries=0' $PLAYLIST > /dev/null
then
  exit
fi
[ $PLAYLIST = radio.ram ] && PLAYER=gxine
[ $PLAYLIST = radio.rm ] && PLAYER=gxine
[ $PLAYLIST = radio.rpm ] && PLAYER=gxine
if grep 'mms://' $PLAYLIST > /dev/null
then
  PLAYER=gxine
fi
[ -z $PLAYLIST ] || exec $PLAYER $PLAYLIST
