#!/bin/sh
#
# Radiostation is a small console port of the KDE Radio Station program.
# http://kderadiostation.coolprojects.org/
# Copyright (C) 2003, 2004 Josef Spillner <spillner@kde.org>
# Published under GNU GPL conditions.
# Version 0.3

: ${DIALOG=dialog}

maindialog()
{
tempfile=`tempfile 2>/dev/null` || tempfile=/tmp/test$$
trap "rm -f $tempfile" 0 1 2 5 15

stationlist=`cat ~/.radiostation.list`

eval $DIALOG --clear --item-help --extra-button --extra-label \
\"Synchronize\" --title \"Radio Station\" --menu \
\"Select your favorite radio station\\\\nand enjoy the music...\\\\n\\\\n\" \
20 78 12 $stationlist \
2> $tempfile
}

updateprocess()
{
url=http://www.kstuff.org/radio/console.php

uptmp=/tmp/`echo radiostation.$$`

lynx -width=200 -dump $url > $uptmp
lines=`wc -l $uptmp | cut -d " " -f 1`

tail -$[$lines-1] $uptmp | \
while read station; do
	read uri; read type; read bandwidth; read style; read location;
	echo -n " \\";
	echo -ne "\n";
	echo -n "\"$uri\" \"$station\" ";
	echo -n "\"$style :: $bandwidth\"";
done
echo ""

rm -f $uptmp
}

syncdialog()
{
tmp=~/.radiostation.list.tmp
rm -f $tmp
{ updateprocess > $tmp; cp $tmp ~/.radiostation.list; echo "READY!" >> $tmp; } &
$DIALOG --title "Synchronization" --clear --tailbox $tmp 20 70
rm $tmp
}

play()
{
cache=~/.radiostation.current.pls
wget -O $cache $1
$2 $cache >/dev/null 2>&1 &
}

playerdialog()
{
tempfile=`tempfile 2>/dev/null` || tempfile=/tmp/test$$
trap "rm -f $tempfile" 0 1 2 5 15

echo "\" xmms\" \"XMMS\" \\" > $tempfile
echo "\"trplayer\" \"TRPlayer\" \\" >> $tempfile
echo "\"mplayer\" \"MPlayer\" \\" >> $tempfile
echo "" >> $tempfile
playerlist=`cat $tempfile`

eval $DIALOG --clear \
--title \"Media player selection\" --menu \
\"Select your favorite player\\\\n\\\\n\" \
15 41 7 $playerlist \
2> $tempfile
choice=`cat $tempfile`
grep -v "^mediaplayer=" ~/.radiostation.settings > $tempfile
mv $tempfile ~/.radiostation.settings
echo "mediaplayer=$choice" >> ~/.radiostation.settings
}

welcome()
{
$DIALOG --title "Radio Station Setup" --clear \
--msgbox "It seems you're running this program for the \
first time. To get ready, the current list of radio stations \
will be fetched. Later on synchronization can always be done \
manually." 10 41
syncdialog
}

tryplay()
{
mediaplayer=`grep "^mediaplayer=" ~/.radiostation.settings | cut -d "=" -f 2`
mediaplayer=`echo $mediaplayer | cut -d " " -f 2`
if test "x$mediaplayer" = "x"; then
  playerdialog
  tryplay $1
else
  play $1 $mediaplayer
fi
}

run=yes

while test "x$run" = "xyes"; do

test -f ~/.radiostation.list || welcome

maindialog
retval=$?

choice=`cat $tempfile`; rm $tempfile

case $retval in
  1) run=no;;
  255) run=no;;
  3) syncdialog;;
  0) tryplay $choice;;
esac

done

clear

