#!/bin/bash
# catchsch - capture "Schickele Mix" - 11PM Saturdays

# For capturing the stream 
DATE=`/bin/date +%F`  # Save the date as YYYY-MM-DD
YEAR=`/bin/date +%Y` # Save just the year as YYYY
FILE=/media/mp3/radio/schickele.$DATE.mp3
STREAM=http://wnyc.org/stream/wnycfm.pls
DURATION=1.1h # enough to catch the show, plus a bit
#DURATION=30s # for testing

# For the RSS syndication 
XML="/media/rss/schickele.rss" # file for the RSS feed
ITEMS=15  # Maximum items in RSS list
XTITLE="Schickele Mix - $DATE Broadcast"  
XDATE=`date -R` # Date in RFC 822 format for RSS
i=\$i ; o=\$o ; m=\$m # replace "$" in the perl script 

# For the id3v2 Tags
AUTHOR="Peter Schickele"
ALBUM="WNYC Stream Rip"
TITLE="Schickele Mix - $DATE"

# Use mplayer to capture the stream 
# at $STREAM to the file $FILE 
/usr/local/bin/mplayer -really-quiet -cache 128 \
    -dumpfile $FILE -dumpaudio -playlist $STREAM &  
# the & turns the capture into a background job
 
/bin/sleep $DURATION  # wait for the show to be over
 
/bin/kill $! # end the stream capture
 
# Tag the resulting captured .mp3
/usr/bin/id3v2 -a "$AUTHOR" -A "$ALBUM" \
    -t "$TITLE" -y $YEAR -T 1/1 -g 255 \
    --TCON "Radio" $FILE

# Add a new entry in the rss file, 
# keep the file to a max of $ITEMS entries, 
# and change the file's date to right now.
/usr/bin/perl -e "use XML::RSS; use XML::Simple; \
    $i=XMLin('$XML');$o=$i;bless $o,XML::RSS; \
    $m=$i->{channel}{item};if((ref $m)ne ARRAY) \
    {$o->add_item(%$m);} else \
    {foreach $m (@{$m}) {$o->add_item(%$m);}} \  
    $o->channel(lastBuildDate=>'$XDATE', \
    pubDate=>'$XDATE'); \
    $o->add_item(title=>'$XTITLE', \
    link=>$o->{'channel'}{'link'}, \
    pubDate=>'$XDATE', \
    enclosure=>{url=>'file://$FILE', \
    length=>(stat('$FILE'))[7], \
    type=>'audio/mpeg'}, mode=>'insert'); \
    pop(@{$o->{'items'}}) \
    while (@{$o->{'items'}}>$ITEMS); \
    $o->{encoding}='UTF-8'; $o->save('$XML');"

/bin/echo "Caught Schickele Mix."

