#!/usr/bin/perl -w
#
# Copyright 2000, 2001 Tivano Software GmbH. This software is
# distributed under the terms of the GNU General Public License. See
# COPYING for additional information.
#
# This is a hacked-up replacement for "amlabel" to label CD-RWs
# intended for use with cdrw-taper

use strict;

# Path to taperlib.pm
push @INC, "/usr/lib/amanda";

require "taperlib.pm";

##
## No user editable settings below here
##

my $WRITE_TAPELIST = 1;
my $FORCE_WRITE = 0;
while ($#ARGV >= 0 && $ARGV[0] =~ /^-.*/) {
    if ($ARGV[0] eq "-f") {
        $FORCE_WRITE = 1;
    } elsif ($ARGV[0] eq "--no-tapelist-entry") {
        $WRITE_TAPELIST = 0;
    } else {
        print "Illegal argument: ".$ARGV[0]."\n";
        usage();
    }
    shift @ARGV;
}

if ($#ARGV < 1) {
    usage();
}

my $CONFIG    = shift @ARGV;
my $NEW_LABEL = shift @ARGV;

my $taper = new Amanda::Taper($CONFIG, \&error);

my ($slot, $writeDev) = $taper->loadSlot("current");
my $mountDev;
if ($writeDev =~ /^(.*?):/) {
    $mountDev = $1;
    $writeDev = $';
} else {
    $mountDev = $taper->{AMANDA_CONF}->{tapedev};
}

if ($NEW_LABEL !~ $taper->{AMANDA_CONF}->{labelstr}) {
    error("Label $NEW_LABEL does not match labelstring \"$taper->{AMANDA_CONF}->{labelstr}\".");
}

# If $FORCE_WRITE is not specified, check first if an empty or unused
# disk is in the drive and if the given label is not on an active
# amanda disk
if (!$FORCE_WRITE) {
    # Don't use a label that's on an active disc
    if (!$taper->is_usable($NEW_LABEL)) {
	error("Cannot overwrite active disk!");
    }
}

my $mediaInfo = new Amanda::Taper::MediaInfo($taper);
if (! $mediaInfo->isErasable()) {
    error("Won't label non-erasable media!");
}

# Write the label file to a temporary directory
mkdir("/tmp/amlabel-cdrw.$$", 0755) || error("Cannot make directory /tmp/amlabelcd.$$: $!");
open LABEL, ">/tmp/amlabel-cdrw.$$/AMANDA_LABEL" or error("Cannot create label: $!");
print LABEL "$NEW_LABEL\n";
close LABEL;

if ($mediaInfo->getType() eq "CDRW") {
    # Exit silently on errors. mkisofs/cdrecord already generate
    # appropriate messages
    my $result = system("$taper->{MKISOFS} -J -R -pad -quiet /tmp/amlabel-cdrw.$$ | $taper->{CDRECORD} dev=$writeDev -data blank=fast -");
    error("Error writing CD-RW") if ($result / 256 != 0);
} else { # DVD
    my $result;
    if ($mediaInfo->needFormat()) {
        $result = system("$taper->{DVDRWFORMAT} $mountDev");
        if ($result / 256 != 0) {
	    error("Error formatting ".$mediaInfo->getType());
        }
    }
    $result = system("$taper->{GROWISOFS} -Z $mountDev -J -R -pad -quiet /tmp/amlabel-cdrw.$$");
    if ($result / 256 != 0) {
	error("Error writing ".$mediaInfo->getType());
    }
}

# Clean up temporary files
if (-e "/tmp/amlabel-cdrw.$$/AMANDA_LABEL") {
    unlink "/tmp/amlabel-cdrw.$$/AMANDA_LABEL";
}
if (-d "/tmp/amlabel-cdrw.$$") {
    rmdir "/tmp/amlabel-cdrw.$$";
}

if ($WRITE_TAPELIST) {
    # Finally, append the new entry to the media list
    open(ML, ">>$taper->{AMANDA_CONF}->{tapelist}")
	|| error("Cannot write to $taper->{AMANDA_CONF}->{tapelist}: $!");
    print ML "00000000 $NEW_LABEL reuse\n";
    close ML;
}

exit 0;

# print an error message and exit
sub error {
  # Clean up temporary files
  unlink "/tmp/amlabel-cdrw.$$/AMANDA_LABEL" if -e "/tmp/amlabel-cdrw.$$/AMANDA_LABEL";
  rmdir "/tmp/amlabel-cdrw.$$" if -d "/tmp/amlabel-cdrw.$$";
  print STDERR "amlabel-cdrw: $_[0]\n" if $_[0];
  exit 1;
}

sub usage {
    print STDERR "Usage: amlabel-cdrw [-f] [--no-tapelist-entry] <conf> <label>\n";
    exit 1;
}

