#!/usr/bin/perl
# Not any more really simple script to test the .scrobbler.log
# brought to you by noleti@29.05.06

use Audio::Scrobbler; #patched version, originally from CPAN
use Getopt::Std;
use FileHandle;

my $infile=".scrobbler.log";
my $infileTimeless=".scrobbler-timeless.log";
my $ver="0.1";
my ($utc_offset,$idstring,$idnumber);
my $date = time;
my $totaltime=0;
my $fh = new FileHandle;

my $info=<<EOI;
 
-- Sorry: Invalid arguments!
-- Valid arguments are:
--
-- -u Username
-- -p password
-- -f logfile   OR
-- -d directory (e.g. foo/)
-- -t UTC_OFFSET (numerical)
-- -h (display help)
-- -n (no utc clock available)
-- -v (for verbose, to get ignored and submitted.log)
-- -D (for DEBUG)
--
-- Real life example:
-- perl rockscrobbler.pl -u noleti -p foo -f E:\\.scrobbler.log -t -2
-- Or Unix-like:
-- perl rockscrobbler.pl -u noleti -p foo -d /media/H100/ -n -D
EOI

getopts('u:p:f:vd:Dt:hn') or die $info;


# Process the password and username
if ((!$opt_u)||(!$opt_p)){
  print "You must supply your last.fm password and username\n";
  exit 1;
}

if ($opt_f) {
    $infile=$opt_f;  
    $infileTimeless=undef;  
    print "file provided\n";
} elsif ($opt_d){
  # We have a path, lets assemble the full name here
  # maybe check for trailing slash/bashslash?
  $infile=$opt_d.$infile;
  $infileTimeless=$opt_d.$infileTimeless;
  print "path provided, built $infile and $infileTimeless \n";
}


my $msg=<<EOMSG;
----------RockScrobbler.pl----------------
-- This is RockScrobbler, trying to     --
-- submit your songs to last.fm         --
--                                      --
-- Version $ver.2                        --
-- Send Bugs to noleti\@gmx.de           --
--                            -- enjoy! --
------------------------------------------
EOMSG

print $msg;


# Lets try to open the input file, I love perl ;)
if (!$fh->open("+<$infile") && !$fh->open("+<$infileTimeless")){
  print "Unable to open input file $infile or $infileTimeless \n";
  exit 1;
}

my @file=<$fh>;

# erase the files contents
$fh->seek(0, 0);
$fh->truncate(0);

# Parse the header section of the log file
# We dont care about first line, do we?
if ($file[1]=~/^\#TZ\/(.*)$/){
  if ($1 ne "UNKNOWN") {
    $utc_offset=$1;
    # Now, if we are allowed to write somethinge like UTC-2 then...
    $utc_offset=~s/^(UTC|GMT)([-+]\d+)$/$2/;
  }
}

# Third line: ID string
if ($file[2]=~/^\#CLIENT\/(.*)$/){
  $idstring=$1;
  $idstring=~s/\s+([\d\.]+)\s*$//;
  $idnumber=$1;
  print "-- Log by $idstring ver. $idnumber         --\n";
}

# The user can override the logfile utc_offset by specifying -t VALUE
if ($opt_t){
    $utc_offset=$opt_t;
}

# This assumes that Rockbox is set to localtime
# If rockbox is set to a different timezone than 
# this computer you have to manually set the offset

if (!defined $utc_offset){
  my @g = gmtime();
  my @l = localtime();
  $utc_offset=($l[2]-$g[2]) %24;
  $utc_offset-=24 if ($utc_offset>12);
  print "-- Guessing UTC offset $utc_offset                --\n";
} else {
  print "-- taking provided UTC offset $utc_offset         --\n";
}
print "------------------------------------------\n";

# Initialize the scob object
$scrob = new Audio::Scrobbler(cfg=>{username => $opt_u, password=>$opt_p,progname=>"roc",progver=>$ver});
if (!defined $scrob->handshake()){print "failed handshaking, aborting\n";exit 1;}



if ($opt_v){
  open SUBFILE,">>submitted.log";
  open IGNFILE,">>ignored.log";
}

foreach my $line (@file){
  if (($line=~/(\d+)\t[LS]\t\d+$/)&&($1>=30)){
    $totaltime +=  $1;
  }  
}

$date -=  $totaltime;


foreach my $line (@file){
  chomp $line;
  if ($line!~/^\#/){
    my $playtime=0;    
    # Take care of an early bug in the rockbox patch
    $line=~s/\t\t\t/\t\t/g;
    my @array=split /\t/,$line;
    # Check the requirements to submit here, wasn't skipped and length>30 seconds
    if (($array[5] eq "L") && ($array[4]>=30)) {
      if ($opt_n){
        $playtime=gmtime($date += $array[4]);
      } else {
        $playtime=$array[6]-3600*$utc_offset;
      }
      $scrob->submit({artist => $array[0], album => $array[1], title => $array[2], length=>$array[4], playtime => $playtime});
      print SUBFILE "$line\n" if ($opt_v);
    } else {
      print IGNFILE "$line\n" if ($opt_v);
    } 
    print "$array[5]: Artist: $array[0]| Album: $array[1]| Track: $array[2]| Lenght.: $array[4]|UTC Playtime: ".gmtime($array[6]-3600*$utc_offset)."|local Playtime: ".gmtime($array[6])."|faked playtime".gmtime($date += $array[4])."| submitted ".gmtime($playtime)."\n";
  } else {
    $fh->print("$line\n");
  }
}
$fh->close();
