#!/usr/bin/perl

# Copy dvd with dvdbackup

sub trim {
    my $s = shift;
    $s =~ s/^\s+|\s+$//g;
    return $s
}

sub printHelp {
    print 
"Usage: $0 [source]
    source: Dvd device to rip from
            Defaults to /dev/cdrom

Error-codes:
    0 - Success
    2 - Destination folder already exists
    * - Some unexpected error
"
}

my $startTime = `date +%s`;
my $source = "/dev/cdrom";
if($ARGV[0] eq "help" || $ARGV[0] eq "--help"){
    printHelp;
    exit 0;
} elsif($ARGV[0]) {
    $source = $ARGV[0];
}

my $dest = "/home/julian/Videos/dvds/";
my $title = `lsdvd /dev/cdrom | grep "Disc Title"`;

if($? != 0){
    print "Failed reading dvd ($source). Could not get title\n";
    exit(1);
}

$title = trim `echo $title | sed 's/Disc Title: //'`;

print "Ripping dvd $title ($source) to $dest\n";

if(-d $dest . $title) {
    print "Destination folder already exists!\n";
    exit 2;
}

my $exitcode = system("dvdbackup -i $source -o $dest -M -n $title");
# $exitcode >>= 8;

my $now = `date +%s`;
my $elapsedTimeSeconds = $now - $startTime;
my $elapsedTimeMinutes = $elapsedTimeSeconds / 60.0;
my $elapsedTimeFormatted = sprintf "%.1f", $elapsedTimeMinutes;

if($exitcode == 0) {
    print "Success!\nRipping took $elapsedTimeFormatted min\n";
    system 'notify-send "DVD $title ripped successfully in ' . $elapsedTimeFormatted . ' min!!!"';
    system "mplayer /usr/share/sounds/freedesktop/stereo/bell.oga 2&> /dev/null";
} else {
    print "Error!\nRipping took $elapsedTimeFormatted min\n";
    system 'notify-send "Error ripping DVD $title !!!"';
    system "mplayer /usr/share/sounds/freedesktop/stereo/bell.oga 2&> /dev/null";
}
# `eject $source`;