#!/usr/bin/perl

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


# Saves the content of the GiantDisc database in the *.tri and *.cdi info files
# or in the metatags.


use lib '/home/music/bin';
use gdparams;
use gdgentools;
use DBI;
use Cwd;	# get current working dir

use Getopt::Long;



my ($help, $albums, $tracks, $metatags);


$Getopt::Long::autoabbrev=1;
GetOptions(
	"albums" 	=> \$albums,
	"tracks" 	=> \$tracks,
	"metatags"	 	=> \$metatags,
#	"resdir:s"	=> \$resdir,
	"help" 		=> \$help 
	);

if ($help || !($albums || $tracks | $metatags)){
print <<EndOfTxt;
gdexportdb.pl: Export GiantDisc database content
Option         

--albums

--tracks

--metatags          Export database content (artist, title, tracknumber) 
                    to metatags.
                    Currently only mp3 files are supported.

--help
           
EndOfTxt
exit 0;
}



### main
### Init constants
my $dbh;
my $mp3base = gdparams::gdbase();		# music files base
my $dirbase = cwd();
if($dirbase ne $mp3base){
  print ("Change to the base directory ($mp3base) and call this script again.\n");
  exit;
}

### Open database connection
print ("### Open database connection\n");

$dbh = DBI->connect("DBI:mysql:GiantDisc", "music", undef)
    or die "unable to connect to GiantDisc db";

open(WARN, ">gdbackupdb-warnings.txt");



### Track
if ($tracks){
  print ("\nCreate Track Info files (.tri) \n\n");
  make_tri($mp3base);
}

### Album
if ($albums){
  print ("\nCreate Album Info files (.cdi) \n\n");
  make_cdi($mp3base);
}

### ID3
if ($metatags){
  print ("\nAdd/Update ID3 tags (.tri) \n\n");
  save_metatags($mp3base, 0);
}




close WARN;

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

exit;



###############################################################################

###################
### TRACK Infos ###
###################


sub make_tri{ #
  my ($mp3base) = @_;
  my $mp3file;

  ### Get all track records
  my $trackh = $dbh->prepare('SELECT * FROM tracks');
  #my $trackh = $dbh->prepare('SELECT * FROM tracks WHERE sourceid="3011f514"');
  my $nbtracks = $trackh->execute;
  
  print("nbtracks = $nbtracks \n");
  while($trackrow = $trackh->fetchrow_hashref){

    $mp3file = `ls [0-9][0-9]/$trackrow->{mp3file}`;
    chop($mp3file);
    if(length($mp3file)<2){
      print (WARN "WARNING: could not find $trackrow->{mp3file}\n");
      print ("\n\nWARNING: could not find $trackrow->{mp3file}\n");
      print ("         sending .tri file to directory 00/ \n");

      $mp3file = "00/$trackrow->{mp3file}";
    }
    
    $mp3file =~ s/.mp3/.tri/;
    $lyrfile = $mp3file;
    $lyrfile =~ s/.tri/.txt/;

    ### Write .tri file
    if ($trackrow->{tracknb} == 1) {print ("\n\n");}
    print("$mp3file "); 
    open(TRI, ">$mp3file");

    print(TRI "TRACK=$trackrow->{tracknb}\n");
    print(TRI "TARTIST=$trackrow->{artist}\n");
    print(TRI "TTITLE=$trackrow->{title}\n");
    print(TRI "TGENRE1=$trackrow->{genre1}\n");
    print(TRI "TGENRE2=$trackrow->{genre2}\n");
    print(TRI "TYEAR=$trackrow->{year}\n");
    print(TRI "TLANG=$trackrow->{lang}\n");
    print(TRI "TTYPE=$trackrow->{type}\n");
    print(TRI "TRATING=$trackrow->{rating}\n");
    print(TRI "TLENGTH=$trackrow->{length}\n");
    print(TRI "TSOURCE=$trackrow->{source}\n");
    print(TRI "TSOURCEID=$trackrow->{sourceid}\n");
    print(TRI "TCONDITION=$trackrow->{condition}\n");

    print(TRI "TVOLADJUST=$trackrow->{voladjust}\n");
    print(TRI "TLENGTHFRM=$trackrow->{lengthfrm}\n");
    print(TRI "TSTARTFRM=$trackrow->{startfrm}\n");
    print(TRI "TBPM=$trackrow->{bpm}\n");
    print(TRI "TBITRATE=$trackrow->{bitrate}\n");
    
    print(TRI "TCREATED=$trackrow->{created}\n");
    print(TRI "TMODIFIED=$trackrow->{modified}\n");

    close(TRI);


    ### Write .txt file (lyrics)
    if (length($trackrow->{lyrics}) > 0) {
      print("LYRICS-FILE:$lyrfile "); 
      open(LYR, ">$lyrfile");
      print(LYR $trackrow->{lyrics});
      close(LYR);
    }
  }
  $trackh->finish;

}


###############################################################################

###################
### ALBUM Infos ###
###################


sub make_cdi{ #
  my ($mp3base) = @_;
  my $cdifile;

  ### Get all album records
  my $albumh = $dbh->prepare('SELECT * FROM album');
  my $nbalbums = $albumh->execute;
  
  print("nbalbums = $nbalbums \n");
  while($albumrow = $albumh->fetchrow_hashref){

    $cdifile = "00/cd0x$albumrow->{cddbid}.cdi";
    
    ### Write .cdi file
    if ($albumrow->{tracknb} == 1) {print ("\n\n");}
    print("$cdifile "); 
    open(TRI, ">$cdifile");

    print(TRI "AARTIST=$albumrow->{artist}\n");
    print(TRI "ATITLE=$albumrow->{title}\n");
    print(TRI "CDDBID=$albumrow->{cddbid}\n");

    close(TRI);

  }
  $albumh->finish;

}

###############################################################################

################
### ID3 Tags ###
################


sub save_metatags{ #
  my ($mp3base, $force_writing) = @_;
  my ($audiofile, $trackh, $tracknb, $nbtracks, $extitle, $exartist);
  my ($album, $albumh, $nbalbums, $extalbum, $exyear, $exgenre);

  ### Get all track records
  $trackh = $dbh->prepare('SELECT * FROM tracks');
  #$trackh = $dbh->prepare('SELECT * FROM tracks WHERE sourceid="ed0f1010"');
  $nbtracks = $trackh->execute;
  $tracknb = 0;
  
  print("nbtracks = $nbtracks \n");
  while($trackrow = $trackh->fetchrow_hashref){
#    if(($tracknb % 10) == 0) {print($tracknb);}

    $audiofile = gdgentools::get_full_audiofile_path($trackrow->{mp3file});
    if (gdgentools::audio_filetype($audiofile) eq "mp3"){
      ### Filetype  is mp3
      if(length($audiofile)<2){
        print (WARN "WARNING: could not find $trackrow->{mp3file}\n");
        print ("\n\nWARNING: could not write to $trackrow->{mp3file}\n");
      }
      else{
        ### Get album info
        $album = "";
        $albumh = $dbh->prepare("SELECT * FROM album WHERE cddbid='$trackrow->{sourceid}'");
        $nbalbums = $albumh->execute;
        if ($albumrow = $albumh->fetchrow_hashref){
        	$album = $albumrow->{title};
        }
        $albumh->finish;
  
        $trackrow->{artist} =~ s/"/''/g;
        $trackrow->{title}  =~ s/"/''/g;
        $album              =~ s/"/''/g;
        $id3genre		  = "12"; 		# 12: Other
  
        ($exartist, $extitle, $exalbum, $exyear, $exgenre) =
          split /\n/, `mp3info -p "%a\\n%t\\n%l\\n%y\\n%t" "$audiofile"`;
  
        # max length of id3 title/artist/album is 30 characters
        $trackrow->{artist}= substr($trackrow->{artist},0, 30); 
        $trackrow->{title} = substr($trackrow->{title}, 0, 30); 
        $album             = substr($album, 0, 30); 
  
        # eat trailing space
        if($trackrow->{title} =~ m/(.*\w) +$/) {$trackrow->{title} =$1;} 
        if($trackrow->{artist}=~ m/(.*\w) +$/) {$trackrow->{artist}=$1;} 
        if($album             =~ m/(.*\w) +$/) {$album             =$1;} 
  
        if(  $trackrow->{artist} ne $exartist
          || $trackrow->{title}  ne $extitle
          || $album              ne $exalbum
          || $trackrow->{year}   ne $exyear
         #|| genre?
          ){
          ### Write id3 tags
          if ($trackrow->{tracknb} == 1) {print ("\n\n");}
          print("UPDATING:$audiofile: $trackrow->{artist}, $trackrow->{title}\n");  
          print("$audiofile\nINT: $trackrow->{title}, $trackrow->{artist}, $album\nEXT: $extitle, $exartist, $exalbum\n");  
          system("mp3info "
          	 ." -a \"$trackrow->{artist}\" "
          	 ." -t \"$trackrow->{title}\" "
          	 ." -l \"$album\" "
          	 ." -y \"$trackrow->{year}\" "
          	 ." -g \"$id3genre\" "
          	 ." ".$audiofile
          	);
          print("$trackrow->{artist} / $trackrow->{title}\r");
        }
        #else{print("up to date: $trackrow->{title}\n");}
      }
    }# end if filetype == mp3
  }
  $trackh->finish;

}




