#!/usr/bin/perl

# This script rips "The Writer's Almanac" daily.  It could easily be
# generalized to other shows.  It requires a crontab entry like this one:

# 30 7    * * *   cd ~/bin/Streamripper ; ~/bin/Streamripper/rip-writers-almanac.pl -u http://wxpr.dwave.net:8005/wxpr64k -d 30 -l 290

# Since iTunes is not guaranteed to be running, we have a holding
# directory.  After each rip, we try to copy all files to the holding
# directory, and purge if we're successful.  Finally, we try to delete
# any listened-to rips from iTunes.

# If you have questions about the script, email me: mark-abbott@earthlink.net

# 2005-03-21
# Generalized to allow ripping from different stations.


use strict;

my $g_d_holding = '/tmp/streamripper-holding';
mkdir($g_d_holding) unless -e($g_d_holding);
my $g_playlist = 'Ripped';

our ($opt_d, $opt_u, $opt_l);
use Getopt::Std;
getopts('d:u:l:');

# Delay -d seconds.  
sleep($opt_d) if $opt_d;

# Get the stream.
# Files are saved in a format like this:
#   sr_program_2005_03_16_11_43_14.mp3

system('/usr/local/bin/streamripper',
#     'http://war.str3am.com:8050/',
       $opt_u,
       '-l', $opt_l || 300,	# 5 minutes
       '-d', $g_d_holding,	# Holding directory
       '-s',	# Don't make a separate directory for each stream
       '-a',	# Filename.
);


# Copy the holding directory to iTunes.

require 'tell_itunes.pm';
my $script_template =

<<SCRIPT_TEMPLATE;
try
 with timeout of 1500 seconds
  set t_imported to add POSIX file "\%s" to playlist "$g_playlist"
 end timeout
end try
SCRIPT_TEMPLATE

foreach my $f (glob "$g_d_holding/*.mp3")
{
    #warn "need to copy $f to iTunes.\n";
    my $script = sprintf($script_template, $f);
    &tell_itunes($script);
    #warn "unlink $f";
    unlink($f);
}

# Purge heard files from iTunes.

#warn "need to purge heard files.\n";

my $list_script =

<<LIST_SCRIPT;
  set trackList to tracks in playlist "$g_playlist"
  repeat with i from 1 to count of trackList
    set thisTrack to item i of trackList
    if played count of thisTrack > 0 then
      set thisDBID to database ID of thisTrack
      delete (every track of playlist "Library" whose database ID = thisDBID)
    end if
  end repeat
LIST_SCRIPT

&tell_itunes( $list_script );

&tell_itunes( 'update "Monk"' );

