#!/usr/bin/perl

##################################################
#
# GiantDisc mp3 Jukebox
# 
# © 2000, Rolf Brugger
#
##################################################

# gdcdi2txt.pl: Giant Disc, translate one cdi file to a text line
#               the fields are tab separated
#
# takes as arguments the .cdi files to be translated
#
# CALL THIS SCRIPT IN THE DIRECTORY /HOME/MUSIC !
# Output should be redirected to tmp/albumss.txt

use lib '/home/music/bin';
use gdgentools;
use gddb;
use DBI;

### Parse Arguments
if($#ARGV < 0){
  print "Error: at least one .cdi file as argument required\n";
  print "       Option: -n  do not write a database record\n";
  exit(-1);
}

if($ARGV[0] eq "-n"){
  shift;
  $writedb = 0;
  print("Database writing skipped\n");
}
else{
  $writedb = 1;
}

my $dbhost = "localhost";

### Open database connection
print ("### Open database connection\n");
$dbh = DBI->connect("DBI:mysql:GiantDisc", "music", undef)
    or die "unable to connect to GiantDisc db";



for($i=0;$i<=$#ARGV;$i++){
  ### Analyze .cdi file line by line

  $title = $artist = $cdid = '';

  open(CDIFILE, $ARGV[$i]);
  while(<CDIFILE>){
    $line = $_;

    # match: IDENTIFIER=(strings-not-ended-by-whitespace) whitespace

    if($line=~m/^ATITLE=(.*\S)\s*/){
      $title=$1;
    }
    if($line=~m/^AARTIST=(.*\S)\s*/){
      $artist=$1;
    }
    if($line=~m/^CDDBID=(.*\S)\s*/){
      $cddbid=$1;
    } 
  }
  
  $title  = gddb::sql_escape_squotes($title);
  $artist = gddb::sql_escape_squotes($artist);

  print("$title\t");
  print("$artist\t");
  print("$cddbid\t");
  print("\n");

  if($writedb){
    my $sqlcmd = 
           "REPLACE INTO album "
          ."(artist,title,cddbid) "
          ."VALUES "
          ."('$artist','$title','$cddbid') ";

    #print("$sqlcmd \n");
    $dbh->do($sqlcmd);
  }

  close(CDIFILE);
}

print ("recalculate genre/language frequencies\n");
system("gdrefresh.pl --dbhost $dbhost --trkgenre --trklanguage --albgenre");

print("### close database connection\n");
$dbh->disconnect;


#
