#
# Copyright (c) 1990,1991,1992 The Ohio State University.
# All rights reserved.
#
# Redistribution and use in source and binary forms are permitted
# provided that: (1) source distributions retain this entire copyright
# notice and comment, and (2) distributions including binaries display
# the following acknowledgement:  ``This product includes software
# developed by The Ohio State University and its contributors''
# in the documentation or other materials provided with the distribution
# and in all advertising materials mentioning features or use of this
# software. Neither the name of the University nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
#

#
# Reuse a backup tape, regardless of the rules.
#
# Steve Romig, January 29, 1990.
#

require 'global.defs';
require 'local.defs';
require $yagrip_perl;
require $backuplib_perl;

$options = "d:ht:";
$usage = 
"usage: reuse [-t tape-id] [-d debuglevel] [-h] tape-id*
    -t tape-id		tape-id to be reused
    -d debuglevel	debugging level
    -h			display this message\n";

    #
    # Make sure that we clean up after ourselves if someone wants to kill us.
    #
$SIG{'INT'} = 'handle_interrupts';
$SIG{'HUP'} = 'handle_interrupts';
$SIG{'TERM'} = 'handle_interrupts';
$SIG{'QUIT'} = 'handle_interrupts';

    #
    # Deal with command line arguments...
    #
die $usage if ! &getopt($options);
die $usage if defined($opt_h);

if (! defined($opt_t) && $#ARGV == -1) {
    die "error (reuse): you didn't specify any tape IDs!\n";
}

@tape_id_list = @ARGV;
if (defined($opt_t)) {
    push(@tape_id_list, $opt_t);
}

tape_loop:
  foreach $tape_id (@tape_id_list) {
    #
    # Read the tape DB entry... 
    #
    if (&update_db($tape_db_file, $tape_db_file, $tape_id,
		   "tape_db", $DB_READ, *replace, *add, *result)) {
        #
        # No entry for this tape - can't reuse it!
        #
	warn "warning (reuse): there's no tape with ID $tape_id in the database\n";
	next tape_loop;
    } else {
	if ($result{"flags"} eq "free") {
	    print "Tape $tape_id is already free.\n";
	    next tape_loop;
	} else {
	    &confirm_tape_usage($tape_id, $result{"run_id"}) ||
	      &sigh("");
	}
    }

    &make_log_entry("reuse, reusing tape $tape_id");

    %replace = ();
    $replace{"flags"} = "free";
    %add = ();
    %result = ();

    if (&update_db($tape_db_file,
		   $tape_db_file,
		   $tape_id,
		   "tape_db",
		   $DB_UPDATE,
		   *replace,
		   *add,
		   *result)) {
	warn "\nwarning (reuse): couldn't update the entry for tape $tape_id in the tape database!\n";
    } else {
        print "\nTape $tape_id is now free for use.\n";
    }
}
