#!/bin/sh
#***************************************************************************
# $Copyright: Copyright (c) 2022 Veritas Technologies LLC. All rights reserved $
#***************************************************************************

BPCLIMAGELIST=/usr/openv/netbackup/bin/bpclimagelist

#
# Query the NetBackup server for the list of images.
#

/bin/rm -f /tmp/infx_netbackup_images
/bin/rm -f /tmp/infx_bar_images
/bin/rm -f /tmp/infx_bar_deletes
/bin/rm -f /tmp/infx_oldest_netbackup_bid
/bin/rm -f /tmp/infx_bar_delete_output

$BPCLIMAGELIST -t UBAK -ct 6 -r >/tmp/infx_netbackup_images

OLDEST_BID=2147483647

/bin/cat /tmp/infx_netbackup_images |
while read BID REST
do
	if [ $BID -lt $OLDEST_BID ]
	then
		OLDEST_BID=$BID
		/bin/echo "$OLDEST_BID" >/tmp/infx_oldest_netbackup_bid
	fi
done

if [ ! -f /tmp/infx_oldest_netbackup_bid ] ; then
	/bin/echo "$OLDEST_BID" > /tmp/infx_oldest_netbackup_bid
fi



#
# If we found any NetBackup Informix DB backups, then
# /tmp/infx_oldest_netbackup_bid will be non-empty and will contain the
# backup id of the oldest NetBackup image. Create a list of copyid/aid
# pairs from the Informix DB that have copyids (backup ids) older than
# the oldest Informix backup in the NetBackup DB.
#

/bin/cat /tmp/infx_oldest_netbackup_bid |
while read OLDEST_BID
do

$INFORMIXDIR/bin/dbaccess sysutils - << EOF 1>/dev/null 2>/dev/null
UNLOAD TO /tmp/infx_bar_images DELIMITER ' '
	SELECT ins_copyid_lo, ins_aid FROM bar_instance
	WHERE ins_copyid_lo < ${OLDEST_BID};
EOF
RETURN_STATUS=$?
if  [ "$RETURN_STATUS" -ne "0" ] ; then
	echo "dbaccess returned $RETURN_STATUS"
	exit $$RETURN_STATUS
fi
done




#
# Format DELETE commands for the old backups that are no longer in the
# NetBackup image DB.
#

/bin/cat /tmp/infx_bar_images |
while read BACKUPID AID
do
	/bin/echo "DELETE FROM bar_instance WHERE ins_copyid_lo = ${BACKUPID};" >> /tmp/infx_bar_deletes

	/bin/echo "DELETE FROM bar_action WHERE act_aid = ${AID};" >> /tmp/infx_bar_deletes

done



#
# Do the DELETE commands.
#

if [ -f /tmp/infx_bar_deletes ] ; then
	$INFORMIXDIR/bin/dbaccess sysutils - </tmp/infx_bar_deletes >/tmp/infx_bar_delete_output 2>&1
	RETURN_STATUS=$?
	if  [ "$RETURN_STATUS" -ne "0" ] ; then
		echo "dbaccess returned $RETURN_STATUS"
		exit $$RETURN_STATUS
	fi
else
	/bin/echo "No images in the Informix Catalog" ;
fi

