#!/bin/sh 
###############################################################################
# This script grabs audio stream from predefined FM stations URLs             #
# and saves it in mp3 file. It creates file name from current date and time.  #
# Author: Alexander lazarenko                                                 #
# Date: 06/17/2011                                                            #
###############################################################################
#
# Global variable declaration
#
MPLAYER="/usr/bin/mplayer"
LAME="/usr/local/bin/lame"
WGET="/usr/bin/wget"
RESDIR="/usr/local/share/radio"
DSTDIR="/files/radio"
LOGDIR="/var/log/radio"
NOW=$(date +"%d-%b-%Y_%H-%M")
TODAY=$(date +"%d-%b-%Y")
#
###############################################################################
#
# Help function
#
usage() {
    echo "usage: $0 <radio station> (start|stop)"
    echo "radio stations are:" 
    echo "nashe      -- Nashe Radio"
    echo "nrj        -- Energy FM"
    echo "mayak      -- Mayak24 FM"
    echo "pioner     -- Pioner FM"
    echo "montecarlo -- Radio Monte Carlo"
    echo "silver     -- Silver Rain"
    echo "europeplus -- Europe Plus"
    echo "retrofm    -- Retro FM"
    exit 1
}
###############################################################################
#
# Sets vars according to FM station name from command-line
#
case "$1" in
    'silver')
    RESFILE="http://www.silver.ru/radio/128.m3u"
    PREFIX="silver"
    ARTIST="Silver Rain"
    ;;
    'nashe')
    RESFILE="http://188.127.243.169/nashe-192.m3u"
    PREFIX="nashe"
    ARTIST="Nashe Radio"
    ;;
    'nrj')
    # This guys use snicky algorithm,they use token that changes once a day.
    # If you come not from theyr site and/or without token you just get
    # some commercial crap not music. We should find out token first, then
    # use it as stream URL.
    $WGET --quiet -nv "http://www.energyfm.ru/?an=nrj_online_page" -O /tmp/nrj.tmp
    RESFILE=$(grep filename /tmp/nrj.tmp|awk '
    { split($0,i,"=") }
    { a=i[2] "=" i[3] "=" i[4] "="i [5] }
    { split(a,i,"\"")}
    { print i[2] }
    ')
    rm -f /tmp/nrj.tmp
    PREFIX="nrj"
    ARTIST="Radio Energy"
    ;;
    'mayak')
    RESFILE="$RESDIR/radiomayak_fm.asx"
    PREFIX="mayak"
    ARTIST="Radio Mayak FM"
    ;;
    'pioner')
    RESFILE="$RESDIR/pionerfm.m3u"
    PREFIX="pioner"
    ARTIST="Pioner FM"
    ;;
    'montecarlo')
    RESFILE="$RESDIR/montecarlo.asx"
    PREFIX="montecarlo"
    ARTIST="Radio Monte Carlo"
    ;;
    'europeplus')
    RESFILE="$RESDIR/europeplus.m3u"
    PREFIX="europeplus"
    ARTIST="Evropa Plus"
    ;;
    'retrofm')
    RESFILE="$RESDIR/retrofm.m3u"
    PREFIX="retrofm"
    ARTIST="Retro FM"
    ;;
    'test')
    # This is just for testing of attempts to connect.
    RESFILE="test.com"
    PREFIX="test"
    ARTIST="Testing"
    ;;
    *)
    echo -e "Station name ommited\n"
    usage
    ;;
esac
#
# Creates file name from FM station name and current date and time
FILE="$PREFIX"_"$NOW"
#
# Check if log dir exist and create it if not
if [ ! -d "$LOGDIR" ]; then
    echo "Creating log directory..."
    mkdir "$LOGDIR"
fi
# 
# Perform actio, start or stop
case "$2" in
    'start')
    echo $ARTIST recording...
    echo ================================
    # Creates output folder if doesn't exist
    if [ ! -d "$DSTDIR" ]; then
        echo "Creating destination directory..."
        mkdir "$DSTDIR"
    fi
    echo `date +"%m/%d/%Y %H:%M:%S"`": Grabing audio stream..."
    # Loop makes 5 attemts to connect to server and dump stream to WAV file
    i=1
    # Start of logging mark
    echo `date +"%m/%d/%Y %H:%M:%S"`": ************ Starting $ARTIST ************" >> "$LOGDIR/$PREFIX"_"$TODAY.log"
    while [ ! -e /tmp/$FILE.wav ]; do
        $MPLAYER -v -vo null -vc null -ao pcm:waveheader:file="/tmp/$FILE.wav" -playlist "$RESFILE" >> "$LOGDIR/$PREFIX"_"$TODAY.log"
        # if no output then it was not successful, wait for 10 sec
        if [ ! -e "/tmp/$FILE.wav" ]; then
            echo `date +"%m/%d/%Y %H:%M:%S"`": Something is not right. Attempt #$i, pausing for 10 sec..."
            sleep 10
        fi
        i=$(($i+1))
        # Check if we exceed number of attempts
        if [ $i -gt 5 ]; then 
            echo "Error: mplayer can't connect after 5 attempts."
            exit 3
        fi
    done
    # End of logging mark
    echo `date +"%m/%d/%Y %H:%M:%S"`": ************ Ending $ARTIST ************" >> "$LOGDIR/$PREFIX"_"$TODAY.log"
    # Worst case scenario, connected, dumped stream but somehow didn't create WAV file
    if [ ! -e "/tmp/$FILE.wav" ]; then
        echo "Error: mplayer didn't work well."
        exit 1
    fi
    # Removing mp3 files from destination dir
    if [ ! -e "$DSTDIR/$PREFIX*.mp3" ]; then
        echo `date +"%m/%d/%Y %H:%M:%S"`": Removing files in destination directory..."
        rm -f $DSTDIR/$PREFIX*.mp3
    fi
    # Start to encode WAV into mp3
    echo `date +"%m/%d/%Y %H:%M:%S"`": Encoding mp3 files..."
    $LAME -S -b 192 --ta "$ARTIST" --tt "Air from $NOW" /tmp/$FILE.wav $DSTDIR/$FILE.mp3
    # if mp3 file was not created something went bad
    if [ ! -e "$DSTDIR/$FILE.mp3" ]; then 
        echo "Error: lame didn't work well."
        exit 2
    fi
    # Everything good, removing temporary WAV file
    echo `date +"%m/%d/%Y %H:%M:%S"`": Removing temporary files..."
    rm -f /tmp/$FILE.wav
    # Change ownership for Windows users
    chown angel "$DSTDIR/$FILE.mp3"
    echo `date +"%m/%d/%Y %H:%M:%S"`": Done."
    ;;
    'stop')
    # Check if mplayer for FM station is realy running
    if [ "`ps afx|grep mplayer|grep $PREFIX|wc -l`" -ne "0" ]; then
        echo `date +"%m/%d/%Y %H:%M:%S"`": Stoping $ARTIST recording..."
        # if yes try to quit all mplayer's threads
        ps afx|grep mplayer|grep $PREFIX|awk {'print $1'}|xargs -L 1 kill -3
    else
        # else typing info
        echo "Hmmm... nothing to stop."
    fi
    ;;
    *)
    echo -e "start or stop ommited\n"
    usage
    ;;
esac
