#!/usr/bin/perl -w

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

my @files = @ARGV;

# check the md5sum, so we are sure we didn't fuck up all
my $destdir = "mp3";

unless (-d $destdir) {
  die "$destdir is a file" if -e $destdir;
  mkdir $destdir;
}


system("md5sum *.flac > md5sum");

foreach my $input (@files) {
  my $infos = extract_metaflac($input);
  print Dumper($infos);
  my $basename = $input;
  $basename =~ s/\.flac$//;
  my $wav = $basename . ".wav";
  my $mp3 = $basename . ".mp3";
  my $flac = $basename . ".flac";

  system('flac', '-d', $input) unless -f $wav;

  next if -f $mp3;

  my @execute = ('lame', '-b', '320', '-h');
  if ($infos->{title}) {
    push @execute, '--tt', $infos->{title};
  }
  if ($infos->{tracknumber}) {
    push @execute, 
    '--tn', $infos->{tracknumber};
  }
  if ($infos->{genre}) {
    push @execute,
    '--tg', $infos->{genre};
  }
  if ($infos->{date}) {
    push @execute,
      '--ty', $infos->{date},
  }
  if ($infos->{artist}) {
    push @execute,
      '--ta', $infos->{artist};      
  }
  if ($infos->{album}) {
    push @execute,
    '--tl', $infos->{album};
  }
  push @execute, '--add-id3v2', $wav, $mp3;

  print "Executing ", join(" ", @execute), "\n";
  system(@execute) == 0 or die "$!\n";
  unlink $wav;
  move($mp3, $destdir);
}

system("md5sum -c md5sum");


sub extract_metaflac {
  my $file = shift;
  die "Can't fork: $!" unless defined (my $pid = open(KID, "-|"));
  my %output;
  if ($pid) {
    while (<KID>) {
      if (m/title=(.*)/i) {
	$output{'title'} = $1;
      } elsif (m/artist=(.*)/i) {
	$output{'artist'} = $1;
      } elsif (m/album=(.*)/i) {
	$output{'album'} = $1;
      } elsif (m/date=(.*)/i) {
	$output{'date'} = $1;
      } elsif (m/genre=(.*)/i) {
	$output{'genre'} = $1;
      } elsif (m/tracknumber=(.*)/i) {
	$output{'tracknumber'} = $1;
      }
    }
  } else {
    $ENV{PATH} = "/bin:/usr/bin:/usr/local/bin";
    exec 'metaflac', '--export-tags-to=-', $file;
  }
  return \%output;
}
