#!/usr/bin/perl -w

use Config::IniFiles;
use Data::Dumper;

my @sourcefiles;
my @tracknames;
my $track = 1;

my $cfg = new Config::IniFiles( -file => $ARGV[0] );

die "must set artist" unless ( $cfg->val( 'showdetails', 'artist' ) );
my $artist = $cfg->val( 'showdetails', 'artist' );
die "must set date" unless ( $cfg->val( 'showdetails', 'date' ) );
my $date = $cfg->val( 'showdetails', 'date' );
die "must set venue" unless ( $cfg->val( 'showdetails', 'venue' ) );
my $venue = $cfg->val( 'showdetails', 'venue' );
die "must set genre" unless ( $cfg->val( 'showdetails', 'genre' ) );
my $genre = $cfg->val( 'showdetails', 'genre' );
die "must set year" unless ( $cfg->val( 'showdetails', 'year' ) );
my $year = $cfg->val( 'showdetails', 'year' );
die "must set file glob\n" unless ( $cfg->val( 'showdetails', 'fileglob' ) );
@sourcefiles = glob( $cfg->val( 'showdetails', 'fileglob' ) );
die "no tracks specified\n" unless ( $cfg->val( 'tracks', 'tracks' ) );
@tracknames = $cfg->val( 'tracks', 'tracks' );
die "file count: ", scalar(@sourcefiles), " track names: ", scalar(@tracknames),
  "\n"
  unless ( $#sourcefiles == $#tracknames );    # names and glob count must match
my $album = join( ' - ', $venue, $date );

for ( my $i = 0 ; $i <= $#sourcefiles ; $i++ ) {
    my $outfilebase =
      sprintf( "%02d-%-s", $track, trackname_to_filename( $tracknames[$i] ) );
    my $wavfile = join( '.', $outfilebase, 'wav' );
    my $mp3file = join( '.', $outfilebase, 'mp3' );
    my $convertwav = '';
    if ( $sourcefiles[$i] =~ /flac$/ ) {
        $convertwav = $cfg->val( 'config', 'deflac' );
    }
    elsif ( $sourcefiles[$i] =~ /shn$/ ) {
        $convertwav = $cfg->val( 'config', 'deshn' );
    }
    else {
        die "cannot handle file type for ", $sourcefiles[$i], "\n";
    }
    $convertwav =~ s/\{infile\}/shellquote($sourcefiles[$i])/e;
    $convertwav =~ s/\{wavfile\}/$wavfile/;
    print $convertwav, "\n";
    my $convertmp3 = $cfg->val( 'config', 'mp3cmd' );
    $convertmp3 =~ s/\{title\}/shellquote($tracknames[$i])/eg;
    $convertmp3 =~ s/\{artist\}/shellquote($artist)/eg;
    $convertmp3 =~ s/\{album\}/shellquote($album)/eg;
    $convertmp3 =~ s/\{trackno\}/$track/g;
    $convertmp3 =~ s/\{genre\}/shellquote($genre)/eg;
    $convertmp3 =~ s/\{year\}/shellquote($year)/eg;
    $convertmp3 =~ s/\{wavfile\}/$wavfile/eg;
    $convertmp3 =~ s/\{mp3file\}/$mp3file/eg;
    print $convertmp3, "\n";
    print 'rm ', $wavfile, "\n";
    $track++;
}

exit;

sub trackname_to_filename {
    my $name = shift;
    $name =~ s/\W+/_/g;
    $name =~ s/_+/_/g;
    $name =~ s/^_//;
    $name =~ s/_$//;
    return lc($name);
}

sub shellquote {
    my $name = shift;
    $name =~ s/(\W)/\\$1/g;
    return $name;
}
