#! /usr/bin/perl -w

# chg-userland: a cheesy glue script to connect the scsi-changer 
# kernel module to the AMANDA backup software. 

# assumes userland and eject are on the path.

# Author: Paul Bort

# Turn this on for some debugging messages:
$debug = 0;

$cmd = "\U$ARGV[0]";
$slot = "\U$ARGV[1]";

print "Command $cmd and Slot $slot.\n" if $debug;

$statusfile = "/amanda/Krakow1/changer-status";
$tapedrive = "/dev/nst0";

$firstslot = 0;
$lastslot = 9;
$maxslot = $lastslot - $firstslot + 1;

$retval = 2;                           #Exit code if command unintelligible
$retmsg = "Can't Parse $cmd $slot\n";  #Exit message if command unintelligible
$retchg = "NOUPDATE";                  #Flag to skip updating $statusfile

if ($cmd eq "-EJECT") {
    $result = `eject $tapedrive`;
    print $result if $debug;
    if ($result =~ /No medium found/) {
	$retval = 1;
	$retmsg = "0 No Medium Found\n";
    } else {
	$retval=0;
	$retmsg= "0 $tapedrive\n";
	$retchg = "Empty";
    }
}

if ($cmd eq "-INFO") {
    $result = `userland`;
    print $result if $debug;
=todo
Return real info instead of this hack.
=cut
    open(CHST,$statusfile);
    $curslot = <CHST>;
    $retval=0;
    $retmsg = "$curslot 10 1\n";
}

if ($cmd eq "-RESET") {
    $result = `eject $tapedrive`;
    print $result if $debug;
    $result = `userland unload`;
    print $result if $debug;
    for($i=9,$i<0,$i--) {
	$result = `userland mv s$i s$i`;
	print $result if $debug;
    }
    $result = `userland load 0`;
    $retchg = "0";
    print $result if $debug;
}

if ($cmd eq "-SLOT") {
    #assume we need to know what's currently loaded:
    open(CHST,$statusfile);
    $curslot = <CHST>;
    close CHST;
    #gotta get the current tape out regardless of what we're loading:
    $result = `eject $tapedrive`; #must eject before we can grab tape
    print $result if $debug;
    $result = `userland unload`; #automatically returns it whence it came.
    if (($slot eq "NEXT") or ($slot eq "ADVANCE")) {
	$curslot=$maxslot ? $target=$firstslot : $target=$curslot+1;
    }
    if ($slot eq "PREV") {
	$curslot=$firstslot ? $target=$maxslot : $target=$curslot-1;
    }
    if ($slot eq "FIRST") {
	$target=$firstslot;
    }
    if ($slot eq "LAST") {
	$target=$maxslot;
    }
    if ($slot eq "CURRENT") {
	$target = $curslot;
    }
    $result = `userland load $target`;
    print $result if $debug;
    $retchg = $target;
}

# All done checking for things we understand

print $retmsg;
open(CHST,">$statusfile");
print CHST $retchg if $retchg ne "NOUPDATE";
exit $retval;

