#!/bin/bash

SEARCH=swiss

declare -A stations

stations[groovesalad]=http://somafm.com/groovesalad.pls
stations[beatblender]=http://somafm.com/beatblender.pls
stations[tagstrance]=http://somafm.com/tagstrance.pls
stations[spacestation]=http://somafm.com/spacestation.pls
stations[cliqhop]=http://somafm.com/cliqhop.pls
stations[lush]=http://somafm.com/lush.pls
stations[missioncontrol]=http://somafm.com/missioncontrol.pls
stations[secretagent]=http://somafm.com/secretagent.pls
stations[illinoisstreet]=http://somafm.com/illstreet.pls
stations[di.fm]=http://listen.di.fm/public3/chillout.pls
stations[di.lounge]=http://listen.di.fm/public3/lounge.pls
stations[di.ambient]=http://listen.di.fm/public3/ambient.pls
stations[di.minimal]=http://listen.di.fm/public3/minimal.pls
stations[di.dj]=http://listen.di.fm/public3/djmixes.pls
stations[monkeyradio]=http://groove.monkeyradio.org/
stations[swissgroove]=http://www.swissgroove.ch/listen128.pls
stations[zeitfuerklang]=http://stream.laut.fm:80/zeitfuerklang

if [ $# -ge 1 ] ; then
  SEARCH=$1
fi

case "$SEARCH" in
  http:*)
     URL=$SEARCH
     ;;
  *)
     declare -a resultstations

     for key in "${!stations[@]}" ; do
       case "$key" in
         ${SEARCH}*)
           resultstations[${#resultstations[@]}]=$key
           ;;
         *)
           ;;
       esac
     done

     case ${#resultstations[@]} in
       0)
          echo "Error: Unknown station \"$SEARCH\"" >&2
          echo "known stations:"

          for st in "${!stations[@]}" ; do
            echo "  * $st"
          done
          echo
          exit 1
          ;;
       1)
          key=${resultstations[0]}
          echo "Playing station" $key
          URL=${stations[${key}]}
          ;;
       *)
          echo "multiple stations found:"

          for st in "${resultstations[@]}" ; do
            echo "  * $st"
          done
          echo
          key=${resultstations[0]}
          echo "Playing station" $key
          URL=${stations[${key}]}
          ;;
     esac
     ;;
esac


case "$URL" in
  http*)
    STREAM=`wget -q -O - "$URL" | sed -n -e "s/^File[0-9]*=http/http/p" | head -1`
    ;;
  stream*)
    STREAM=${URL##stream:}
    ;;
  *)
    ;;
esac

if [ "$STREAM" ] ; then
  echo "Playing $STREAM"
  audacious "$STREAM" &
else
  # assume .m3u-style URL-List
  URLS=`wget -q -O - "$URL"`
  audacious $URLS &
fi

