#!/usr/bin/perl -w
# -*- mode: cperl -*-

use strict;
use warnings;
use Data::Dumper;
use File::Copy;

if (@ARGV) {
    show_help() if (($ARGV[0] eq "--help") || ($ARGV[0] eq "-h"));
}

my $infodir = "info";
my $mp3dir = "mp3";
my $flacdir = "flac";

my @wavs;
my @infos;

opendir(my $dh, ".") || die "can't opendir . $!";
@wavs = grep { /\.wav$/ && -f "$_" } readdir($dh);
closedir $dh;

show_help() unless @wavs;

foreach my $destdir ($infodir, $mp3dir, $flacdir) {
    unless (-d $destdir) {
	die "$destdir is a file" if -e $destdir;
	mkdir $destdir;
    }
}

my $discinfo = parse_inf_file("$infodir/audio.cddb");
print Dumper($discinfo);

system("md5sum *.wav > MD5SUMS.txt");

foreach my $input (sort @wavs) {
    my $tracknumber;
  if ($input =~ m/^track(\d\d)\.cdda\.wav$/) {
    $tracknumber = $1;
  } else {
      show_help("This doesn't look as a track from cdparanoia\n");
  }
    my $basename = $input;
    $basename =~ s/\.wav$//;
    my $wav = $basename . ".wav";
    my $mp3 = $basename . ".mp3";
    my $flac = $basename . ".flac";
    my $infofile = "info/audio_$tracknumber.inf";
    my $trackinfo = parse_inf_file($infofile);

    my ($number, $artist, $title, $genre, $date, $album);

    $number = ($trackinfo->{Tracknumber} or $tracknumber);
    $number =~ s/^0+//;

    $artist = ($trackinfo->{Performer} or "Unknown");

    my $trackindex = $number - 1;
    $title = ($trackinfo->{Tracktitle} or $discinfo->{"TTITLE$trackindex"} 
	      or "Unknown");

    $genre = ($discinfo->{DGENRE} or "Unknown");
    my $mp3genre = $genre;
    $mp3genre =~ s/(.+?)\s*,.*/$1/;

    $date = ($discinfo->{DYEAR} or "Unknown");

    $album = ($trackinfo->{Albumtitle} or $discinfo->{DTITLE} or "Unknown");


  my @mpexecute = ('lame', '-b', '320', '-h', 
           '--tt', $title,
           '--tn', $number,
           '--tg', $mp3genre,
           '--tl', $album,
           '--ty', $date,
           '--ta', $artist,
		   '--add-id3v2', $wav, $mp3);

    print "\nExecuting ", join(" ", @mpexecute), "\n\n";

  my @flacexecute = (
             'flac', 
             "--tag=TITLE=$title",
             "--tag=DATE=$date",
             "--tag=ARTIST=$artist",
             "--tag=TRACKNUMBER=$number",
             "--tag=ALBUM=$album",
             "--tag=GENRE=$genre",
             $wav
      );

    print "\nExecuting ", join(" ", @flacexecute), "\n\n";

    system(@mpexecute) == 0 or die "$!\n";
    system(@flacexecute) == 0 or die "$!\n";
    my $targetname = "$tracknumber $artist $title";
    $targetname =~ s![/\\]!!g;
    move($mp3, "$mp3dir/$targetname.mp3");
    move($flac, "$flacdir/$targetname.flac");
}

system("md5sum -c MD5SUMS.txt");


sub parse_inf_file {
    my $target = shift;
    my %info;
    open (my $fh, "<", $target) or show_help("Can't open $target $!\n");
    while (<$fh>) {
	my $line = $_;
    if ($line =~ m/^\s*(\w+)\s*=\s*['"]?\s*(.+?)\s*['"]?\s*$/) {
      $info{$1} = $2;
    }
  }
  close $fh;
  return \%info;
}


sub show_help {
    my $arg = shift;
    print <<'EOF';

I assume the WAVS are in the current directory, generated by something like this:

 cdparanoia -d /dev/sr1 -B -L 

Then I assume the .inf files are in the "info" directory, generated by 

 mkdir info
 cd info
 icedax dev=/dev/sr1 -vall cddb=0 -info-only

EOF
print $arg if $arg;
    exit 1;

}
