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

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

use Tracks;

use File::Temp qw{tempdir};
use File::Spec::Functions qw{catfile splitpath};
use File::Copy;
use File::Path qw{mkpath};
use Getopt::Long qw{:config no_ignore_case no_auto_abbrev};
use Cwd;

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

die "Usage: $0 -o <output.flac> [-D <device>]\n" unless $OUTPUT_NAME;

# output file
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 $tracks = Tracks->new;
$tracks->read_disc($CD_DEVICE);

die "No tracks found; is there a CD in the drive?\n" unless @{ $tracks->get_tracks };

my $tempdir = tempdir(CLEANUP => 1);

my $wav_file  = catfile($tempdir, 'cdda.wav');
my $flac_file = catfile($tempdir, 'cdda.flac');
my $cue_file  = catfile($tempdir, 'cdda.cue');

# rip
my $span = $tracks->get_cdparanoia_span;
system 'cdparanoia', '-d', $CD_DEVICE, $span, $wav_file;
die "\nRipping canceled\n" if ($? & 127);

# encode + cuesheet
open my $CUE, "> $cue_file";
print $CUE $tracks->get_cuesheet;
close $CUE;
system 'flac', '-o', $flac_file, '--cuesheet', $cue_file, $wav_file;
die "\nFLAC encoding canceled\n" if ($? & 127);

# MusicBrainz discid metadata
my $discid = $tracks->get_mbz_discid;

# copy to permanent location
copy($flac_file, $archive_flac);
system 'metaflac', '--set-tag', "MUSICBRAINZ_DISCID=$discid", $archive_flac;
print "Rip saved as $archive_flac\n";
system 'eject', $CD_DEVICE;
