#!/usr/bin/perl -w
use strict;

use FindBin qw{$RealBin};
use lib "$RealBin/lib";

use Ripper;

use File::Spec::Functions qw{catfile splitpath};
use File::Path qw{mkpath};
use Getopt::Long qw{:config no_ignore_case no_auto_abbrev};
use Cwd;
use Audio::FLAC::Header;

GetOptions(
    'device|D=s'  => \my $CD_DEVICE,
    'output|o=s'  => \my $OUTPUT_NAME,
    'force|f'     => \my $FORCE,
    'barcode|b=s' => \my $BARCODE,
);

# output file
die "Usage: $0 -o <output.flac> [-D <device>]\n" unless $OUTPUT_NAME;
my (undef, $out_dir, $out_file) = splitpath($OUTPUT_NAME);
# automatically add ".flac"
$out_file .= '.flac' unless $out_file =~ /\.flac$/;
# default to current directory
$out_dir ||= getcwd;
mkpath($out_dir) unless -e $out_dir;
my $archive_flac = catfile($out_dir, $out_file);

# check for file exist; default to not overwrite
die "$archive_flac exists\nwill not overwrite (use --force to override this)\n" 
    if -e $archive_flac && !$FORCE;

# get the CD info
$CD_DEVICE ||= '/dev/cdrom';

my $ripper = Ripper->new({ device => $CD_DEVICE });
$ripper->rip_to_flac($archive_flac);

if ($BARCODE) {
    print "Writing barcode\n";
    system 'metaflac', '--set-tag', "BARCODE=$BARCODE", $archive_flac;
}

print "Rip saved as $archive_flac\n";
system 'eject', $CD_DEVICE;
