#!/bin/sh

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

unfreeze_force=0

if [ -n "$1" ]
then
	TAPES=$@
else
	TAPES=''
	TAPES_loaded_nonscratch=`vmquery -a -w | awk '$7 ~ /^NONE$/ \
		&& $12 !~ /^00_Scratch$/ && $3 !~ /_CLN$/ { print $1 }'`
	if [ -n "$TAPES_loaded_nonscratch" ]
	then
		for tape in $TAPES_loaded_nonscratch
		do
			printf "Considering ${tape} ..."
			status=`vmquery -m ${tape} | awk -F: ' $1 ~ /^status$/ \
		    { sub("[      ]*0x", "") ; print $NF } '`
			if [ -z "$status" ]
			then
				TAPES="$TAPES $tape"
				echo " in (unallocated)."
			else
				echo " out."
			fi
		done
	fi
fi

if [ -z "$TAPES" ]
then
	echo "Nothing to do!"
	exit 0
fi

echo "Potentially reclaiming `echo $TAPES | wc -w` media: $TAPES"

for tape in $TAPES
do
	bpmedialist -m ${tape} > ${TEMPDIR}/${tape}
	frozen=0
	[ -n "`grep FROZEN ${TEMPDIR}/${tape}`" ] && frozen=1
	cat ${TEMPDIR}/${tape}
	echo

	if [ $frozen -eq 1 ]
	then
		if [ $unfreeze_force -eq 0 ]
		then
			printf "Unfreeze ${tape}? "
			printf "([y]/n/f) "
			read confirm
			[ "`echo $confirm | egrep '^[fF]'`" ] && unfreeze_force=1
			if [ ! "`echo $confirm | egrep '^[nN]'`" ];
			then
				unfreeze=1
			fi
		else
			unfreeze=1
		fi
		if [ $unfreeze -eq 1 ]
		then
			host=`awk '$1 ~ /^Server$/ { print $NF }' ${TEMPDIR}/${tape}`
			echo bpmedia -unfreeze -m $tape -h $host -v
			bpmedia -unfreeze -m $tape -h $host -v
		fi
	fi

	vmquery -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}

	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 '^[nN]'`" ];
		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

	rm ${TEMPDIR}/${tape}
	
done

