#!/bin/bash

function _play
{
  $PLAYER $(wget $_URL --output-document=-| sed -n '/<REF HREF/{s/.*="\(mms.*\)".*/\1/;p}')
}

function _play_ram
{
  $PLAYER $(wget $_URL --output-document=-|cat)
}

PLAYER='mplayer -cache 512'

case $1 in
 1 | 2 | 3) i=$1; let i++;;
 sport+) i=32;;
 news24) i=16;;
 http*) _URL=$1;;
esac
_URL=${_URL:-http://www.rai.tv/mplive/0,,LiveTv^${i},00.html};

TMP_FILE=$(mktemp -p /tmp/tmp);

wget $_URL --output-document=$TMP_FILE

if grep -q "http://mediapolis.rai.it/relinker/" $TMP_FILE; then
  _URL=$(sed -n -e "/http:.*mediapolis.rai.it.relinker/s;.*\(http://mediapolis.rai.it/relinker[^'\"]*\).*;\1;p" $TMP_FILE);
  _play;
elif grep -q 'SRC="/mpASX/' $TMP_FILE; then
  _URL=$(sed -n -e "/SRC=\"\/mpASX\//s;.*SRC=\"\(.*html\).*;\1;p;" $TMP_FILE);
  wget http://www.rai.tv${_URL} --output-document=$TMP_FILE;

  while ! grep -q 'mms://' $TMP_FILE; do
    _URL=$(sed -n -e "/<REF HREF=/{s/.*HREF=.\(.*\)\".*/\1/;p;}" $TMP_FILE);
    if [ "x$_URL" = "x" ]; then
      _URL=$(grep -o 'http://.*x' $TMP_FILE);
    fi
    wget $_URL --output-document=$TMP_FILE
  done
 _play;
elif grep -q 'http://.*.ram' $TMP_FILE; then
  _URL=$(grep -o 'http.*ram' $TMP_FILE| head -n1);
  _play_ram;
elif grep -q 'videoURL.*mms://' $TMP_FILE; then
  $PLAYER $(sed -n '/videoURL.*mms:/{s/.*=.*"\(mms:.*\)".*/\1/;p}' $TMP_FILE)
fi

rm -f $TMP_FILE
