#!/usr/bin/perl

use strict;
#use warnings;

use DBI;
use CGI qw/:standard/;
use File::Basename;
use File::Copy;
use Time::gmtime qw/gmtime/;

my $dbh = DBI->connect("DBI:mysql:radiopar_radioparallaxtest:localhost","radiopar_radiopa",'t0d@y_juni0r')
	or die("Can't connect to radioparallax database: ",DBI->errstr(),"\n");

my $date_str = _build_gmtime_string();
my $prog     = basename($0);

my $sth = $dbh->prepare("SELECT * FROM shows_main ORDER BY show_date DESC, id DESC") 
	or die("Can't prepare statement handle: ",DBI->errstr(),"\n");
$sth->execute() or die("Can't execute query: ",DBI->errstr(),"\n");

my $detail_sth = $dbh->prepare("SELECT * FROM shows_detail WHERE shows_main_id = ? ORDER BY id") 
	or die("Can't prepare statement handle: ",DBI->errstr(),"\n");

print(
	header('text/xml'),
	qq`<?xml version="1.0" encoding="ISO-8859-1"?>
	<rss version="2.0">
		<channel>
			<title>RadioParallax.com Podcast</title>
			<link>http://www.radioparallax.com/</link>
			<description><![CDATA[ 
				Radio Parallax* is a show covering topics in current events, politics, science, technology, history, satire, and whatever we damn well please. The show can be heard in the greater Davis/Sacramento area every Thursday evening from 5:00 p.m. - 6:00 p.m. PST on KDVS, 90.3 FM;
			]]>
			</description>
			<language>en-us</language>
			<pubDate><![CDATA[$date_str]]></pubDate>
			<lastBuildDate><![CDATA[$date_str]]></lastBuildDate>
			<generator><![CDATA[$prog]]></generator>
			<docs><![CDATA[http://www.radioparallax.com/rss]]></docs>
			<managingEditor><![CDATA[webmaster\@radioparallax.com]]></managingEditor>
			<webMaster><![CDATA[webmaster\@radioparallax.com]]></webMaster>	`
);

#my @files = glob("../File/*");

my %seen_mp3 = (); # I don't know WTF is up with some of the data in this table
while(my $row = $sth->fetchrow_hashref()) {	
	my $show_date = $row->{show_date};
	
	# Get detailed info for the show
	$detail_sth->execute($row->{id}) 
		or die("Can't execute query: ",DBI->errstr(),"\n");
		
	while(my $detail_row = $detail_sth->fetchrow_hashref()) {
	
		(my $basename     = $detail_row->{show_segment_url}) =~ s-^.*/--;
		my $mp3_url       = "http://www.radioparallax.com/File/$basename";
		my $mp3_file      = "../File/$basename";
		my $filesize      = -s $mp3_file or next;
		my $segment_title = "Radio Parallax Show: "._reformat_date($row->{show_date});
		(my $show_desc    = $detail_row->{show_segment_description}) =~ s-<[^>]*>--g;
		$show_desc        =~ s/[^\000-\177]//g; # Strip non-ascii chars
		
		if($mp3_url =~ /([ABCDE])\.mp3$/i) {
			$segment_title .= " (Segment ".uc($1).")";
		}	
		
		next if($seen_mp3{$mp3_url});
		$seen_mp3{$mp3_url} = 1;
		
		print(qq`
			<item>
				<title><![CDATA[$segment_title]]></title>
				<description><![CDATA[$show_desc]]></description>
				<enclosure url="$mp3_url" length="$filesize" type="audio/mpeg" />
				<guid isPermaLink="true">$mp3_url</guid>
			</item>
		`);
	}
}

print(qq`
	</channel>
</rss>
`);

#============================================================================
sub _reformat_date {
	my($date) = @_;
	
	my($y,$m,$d) = split(/-/,$date);
	
	return($date) unless($y && $d && $m);

	return(sprintf("%d/%d/%04d",$m,$d,$y));
}

#============================================================================
sub _build_gmtime_string() {
	my @days     = qw(Sun Mon Tue Wed Thu Fri Sat);
	my @months   = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
	my $gm       = gmtime(time);
	
	return(sprintf("%s, %d %s %d %02d:%02d:%02d GMT",
		$days[$gm->wday()],
		$gm->mday(),
		$months[$gm->mon()],
		$gm->year()+1900,
		$gm->hour(),
		$gm->min(),
		$gm->sec()
	));
}