#!/usr/local/bin/perl -w
###########################################
# banshee-ratings-backup
# Mike Schilli, 2011 (m@perlmeister.com)
###########################################
use strict;
use Log::Log4perl qw(:easy);
Log::Log4perl->easy_init($DEBUG);

use DBI qw(:sql_types);
use DBD::SQLite;
use Data::Dumper;
use YAML qw(LoadFile DumpFile);
use Getopt::Std;

getopts( "r", \my %opts );

my $db  = glob 
          "~/.config/banshee-1/banshee.db";
my $dbh = DBI->connect( "dbi:SQLite:$db", 
    "", "", { RaiseError => 1, 
              AutoCommit => 1 });

my $yml     = "banshee-ratings.yml";
my %ratings = ();

if( $opts{ r } ) {
    restore( $yml, $dbh );
} else {
    backup( $dbh, $yml );
}

$dbh->disconnect();

###########################################
sub backup {
###########################################
  my( $dbh, $yml ) = @_;

  my %ratings = ();

  my $sth = $dbh->prepare( 
      "SELECT * FROM CoreTracks" );
  $sth->execute();

  while( my $hash_ref = 
           $sth->fetchrow_hashref() ) {
      next if $hash_ref->{ Rating } == 0;

      $ratings{ $hash_ref->{ Uri } } = 
        $hash_ref->{ Rating };
  }

  DumpFile( $yml, \%ratings );

  $sth->finish();
}

###########################################
sub restore {
###########################################
  my( $yml, $dbh ) = @_;

  my $ratings = LoadFile( $yml );

  for my $song ( keys %$ratings ) {
      DEBUG "Restoring $song";

      my $rating = $ratings->{ $song };

      my $sth = $dbh->prepare(
       "UPDATE CoreTracks SET Rating = ?" .
       "WHERE Uri = ?" );
      $sth->execute( $rating, $song );
      $sth->finish();
  }
}
