#!/usr/bin/perl

# This is the client-side interface for Bacula to drive the VM tape 
#  server.  Format is the same as the plain old mtx-changer:

#  mtx-changer "changer-device" "command" "slot" "archive-device" "drive-index"
#                  $1              $2       $3        $4               $5
#

# Except now "changer-device" is in the form host:port.  For the VM tape 
#  changer, port is usually 50200

use Net::Telnet;

# First we just copy the variables to more useful names.
$server = shift or "localhost:50200"; 
$command = shift or "list";
$slot = shift or 0;
$device = shift or "/dev/ntibm0";
$index = shift or 0;

# Get the device address

$_ = $device;
s/\/dev\/ntibm//;
$tapenum = $_;

$devaddr = "XXXX";
@output = `cat /proc/tapedevices`;
for (@output) {
    my ($tape,$devno,$junk) = split;
    if ($tape eq $tapenum) {
	$devaddr = $devno;
	last;
    }  
}
exit(2) if ($devaddr eq "XXXX");
#$devaddr = ($devaddr eq "XXXX" ? "0181" : $devaddr);
($site,$port) = split(':',$server);

# Get the VM guest name
$guest=`grep 'VM00 Name:' /proc/sysinfo | cut -b 23-30`;
chomp $guest;
$guest =~ s/\s*$//;
exit(2) unless ($guest);

$devaddr = $guest . ':' . $devaddr;

$t = new Net::Telnet(Timeout => 660);
$t->open(Host    => $site,
	 Port    => $port) or exit(6);

@lines = $t->print("$command $slot $devaddr $index");
$rc = $t->getline();
while ($l = $t->getline()) {
	if ($rc == 0) {
	    print $l;
        }
}

exit($rc);

