#!/usr/bin/perl

#      Copyright (C) Philipp 'ph3-der-loewe' Schafft - 2009-2011
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License version 3
#    as published by the Free Software Foundation.
#
#    It is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this software; see the file COPYING.gplv3. If not, write to
#    the Free Software Foundation, 51 Franklin Street, Fifth Floor,
#    Boston, MA 02110-1301, USA.

use strict;
use XML::Simple;
use Data::Dumper;
use LWP::Simple;
use Digest::SHA qw(sha1);

$SIG{'ALRM'} = 'IGNORE';

my %mine2codec = (
                  'application/ogg' => 'ogg_vorbis',
#                  'audio/mpeg'      => 'mpeg',
#                  'audio/aacp'      => 'aacp',
#                  'audio/aac'       => 'aac',
#                  'video/nsv'       => 'nsv',
                 );

my $xml = XMLin($ARGV[0] || 'sc-yp.xml');

my $list = $xml->{'station'};

my $baseurl = 'http://www.shoutcast.com'.$xml->{'tunein'}->{'base'}.'?id=';

#print Dumper($baseurl, $list);

my $type;
my $uuid;
my $c;

foreach my $k (keys %{$list}) {
 $c = $list->{$k};

 $k =~ s/\s*-\s*\[SHOUTcast.com\]$//;

 $c->{'server_name'} = $k;

 $type = $mine2codec{$c->{'mt'}};

 $c->{'playlist_url'} = $baseurl.int($c->{'id'});

 get_playlist($c);

 next unless ($c->{'listen_url'} = $c->{'playlist'}->[2]);

# print Dumper($c, $type);

 print "TITLE=$c->{'server_name'}\n" if $c->{'server_name'};

 print "PLAYLIST=$c->{'playlist_url'}\n";
 print "STREAMURL=$c->{'listen_url'}\n";
 print "SIGNALINFO=codec:$type\n" if defined $type;
 print "GENRE=$c->{'genre'}\n" if $c->{'genre'};

 if ( defined(($uuid = gen_uuid($c))) ) {
  print "HASH={UUID}$uuid\n";
 }

 print "==\n";
}

exit(0);

# ---
sub get_playlist {
 my ($c)  = @_;
 my @pl;
 my ($k, $v, $n);
 my @a = ({'score' => 0});
 local $_;

 eval {
  #local $SIG{'ALRM'} = sub { die; };
  alarm(8);
  @pl = split(/\r?\n/, get($c->{'playlist_url'}));
 };

 return undef unless shift(@pl) eq '[playlist]';

 foreach (@pl) {
  ($k, $v) = /^(.+?)=(.+)$/ or next;

  next if $k =~ /^Length\d/;

  ($k, $n) = $k =~ /^(\D+)(\d*)$/;

  $a[int $n] ||= {};
  $a[int $n]->{$k} = $v;

  if ( $k eq 'Title' ) {
   $v =~ /^\(#\d+ - (\d+)\/(\d+)\)\s+/;
   $a[int $n]->{'score'} = $1/$2;
  }
 }

 @a = sort{$b->{'score'} <=> $a->{'score'}}(@a);

 $a[0]->{'File'} =~ s#^http://#icy://#;

 unless ( length($a[0]->{'File'}) ) {
  $c->{'playlist'} = [undef, undef, undef];
  return;
 }

 $c->{'playlist'} = [\@pl, \@a, $a[0]->{'File'}.'/'];
}

sub gen_uuid {
 use bytes;
 my ($c)  = @_;
 my $hash = '\153\247\270\021\235\255\021\321\200\264\000\300\117\324\060\310'; # URL NS
 my $sha1;
 my $uuid;

 return undef unless length $c->{'listen_url'};

 $hash .= $c->{'listen_url'};

 $sha1 = sha1($hash);

 $uuid = substr($sha1, 0, 16);

 substr($uuid, 6, 1, chr(ord(substr($uuid, 6, 1)) & 0x0f | 0x50));
 substr($uuid, 8, 1, chr(ord(substr($uuid, 8, 1)) & 0x3f | 0x80));

 return join('-',
            map { unpack('H*', $_) }
            map { substr($uuid, 0, $_, '') }
            (4, 2, 2, 2, 6));
}

#ll

__END__
$VAR1 = {
          'station' => {
                       'Kuschel.FM - Das Kuschelradio! - [SHOUTcast.com]' => {
                                                                             'mt' => 'audio/mpeg',
                                                                             'br' => '128',
                                                                             'lc' => '768',
                                                                             'id' => '5875',
                                                                             'ct' => 'Katie Melua - It`s Only Pain',
                                                                             'genre' => 'Lovesongs Balladen'
                                                                           },
                       'FUNDINGUE.COM? \'el VALLENATO a su m?xima POTENCIA!\' - [SHOUTcast.com]' => {
                                                                                                  'mt' => 'audio/mpeg',
                                                                                                  'br' => '48',
                                                                                                  'lc' => '271',
                                                                                                  'id' => '472663',
                                                                                                  'ct' => 'Fundingue 2',
                                                                                                  'genre' => '100  Vallenato'
                                                                                                }
                     },
          'tunein' => {
                      'base' => '/sbin/tunein-station.pls'
                    }
        };
