#!/bin/sh

for robline in `tpconfig -l | awk ' $1 ~ /^robot$/ \
	{ print $2 ":" $4 ":" $NF }'`
do
	robnum=`echo $robline | awk -F: '{ print $1 }'`
	robtype[${robnum}]=`echo $robline | awk -F: '{ print $2 }'`
	robdev[${robnum}]=`echo $robline | awk -F: '{ print $3 }'`
done

function choose_robot {
	i=0
	while [ "${i}" -lt "${#robdev[*]}" ]
	do
		echo "${i} - ${robtype[${i}]}(${i}), ${robdev[${i}]}"
		i=$(( $i + 1 ))
	done
	printf "Which robot? "

	read ROBNUM
}

choose_robot
while [ "$ROBNUM" -lt 0 -o "$ROBNUM" = "-0" -o -z "${robdev[${ROBNUM}]}" ]
do
	echo "Robot number ${ROBNUM} doesn't seem to exist, try again."
	echo
	choose_robot
done

ROBOT=${robdev[${ROBNUM}]}
ROBTYPE=${robtype[${ROBNUM}]}
TEMPDIR=/tmp

PATH=${PATH}:/usr/openv/gr/bin:/usr/openv/netbackup/bin:/usr/openv/netbackup/bin/goodies:/usr/openv/netbackup/bin/admincmd:/usr/openv/volmgr/bin:/usr/openv/volmgr/bin/goodies

for tape in `echo 's p' | tldtest -r $ROBOT \
             | awk '$1 ~ /^Barcode$/ { print $NF }'`
do
	vmquery -m ${tape} > ${TEMPDIR}/${tape}
	if [ ! -s ${TEMPDIR}/${tape} ]
	then
		echo "${tape} is new, no action till barcode rules."
	else
		bpmedialist -m ${tape} > ${TEMPDIR}/${tape}
		inpool=`awk -F: ' $1 ~ /^volume pool$/ {
			sub("^[^(]*", "")
			gsub("[()]", "")
			print $NF
		} ' ${TEMPDIR}/${tape}`
 		status=`awk -F: ' $1 ~ /^status$/ {
			sub("[      ]*0x", "")
			print $NF
		} ' ${TEMPDIR}/${tape}`
		scratch_pool=`vmpool -listscratch | tail -1`
		scratch_num=`vmpool -listall -bx \
			| awk " \\$1 ~ /^$scratch_pool\$/ { print \\$2 }"`
	
		cat ${TEMPDIR}/${tape}
		bpmedialist -m ${tape}
		echo
	
		do_something=0
	
		if [ -z "$status" ];
		then
			printf "${tape} is already deassigned"
			if [ "$inpool" -eq "$scratch_num" ];
			then
				printf " and is already in ${scratch_pool}. "
			else
				printf "; move it to ${scratch_pool}? "
				do_something=1
			fi
		else
			printf "Deassign ${tape} "
			do_something=1
			if [ "$inpool" = "$scratch_pool" ];
				then
				printf "(and leave it in ${scratch_pool})? "
			else
				printf "and move it to ${scratch_pool}? "
			fi
		fi
	
		if [ "$do_something" -gt 0 ];
		then
			printf "(y/[n]) "
			read confirm
			if [ `echo $confirm | egrep '^[yY]'` ];
			then
				[ -z "$status" ] && status=0
				echo vmquery -deassignbyid ${tape} ${inpool} ${status}
				vmquery -deassignbyid ${tape} ${inpool} ${status}
				echo vmchange -m ${tape} -p ${scratch_num}
				vmchange -m ${tape} -p ${scratch_num}
				echo Altered ${tape}...
				vmquery -m ${tape}
			fi
		else
			printf "\n"
		fi
	fi
	rm ${TEMPDIR}/${tape}
done

printf "Inject tapes? ([y]/n) "

read confirm
if [ ! "`echo $confirm | egrep '^[nN]'`" ];
then
	echo vmupdate -rt ${ROBTYPE} -rn ${ROBNUM} \
		-interactive -use_barcode_rules -empty_map
	vmupdate -rt ${ROBTYPE} -rn ${ROBNUM} \
		-interactive -use_barcode_rules -empty_map
fi

