#!/bin/sh
if [ "${1:-}" = "-x" ] ; then set -xv; shift; fi

# Script that returns mt command results of drives enstore knows about

# the user must specify a drive or mount/dismount command
if [ -z "${1-}" ] ; then
  echo "Usage $0 <drive>   <mt-command|uname>"
  exit 1
fi

drive=`echo $1 | tr '[a-z]' '[A-Z]'`
command="${2:-status}"

eval `drive-config.py $drive`
if [ $host = UNKNOWN -o $device = UNKNOWN ];then
  echo $drive $host $device
  exit 1
fi

cmd="enrsh $host 'mt -f $device $command 2>&1 </dev/null; echo \$? 2>&1 </dev/null' </dev/null"
cmd2="x=\"\`$cmd\`\""
echo $cmd

# connection refused are a problem (Don't forget to option nowait.1000 in inetd.conf)
# retries on busys as well
count=0
tries=60

# process the command
while [ $count -le $tries ]; do
  eval $cmd2
  #echo $x
  if [ `echo $x | grep -ci "refused"` -eq 0 -a \
       `echo $x | grep -ci "resource busy"` -eq 0 \
     ] ; then break
  fi
  count=`expr $count + 1`
  sleep 1
done

stat=`echo $x | awk '{print $NF}'`;
echo "$x"
exit $stat
