#!/bin/sh
# $Header: index_clients.sh,v 1.6 2003/04/30 14:21:07 lkampa Stab $
#bcpyrght
#***************************************************************************
#* $VRTScprght: Copyright 1993 - 2002 VERITAS Software Corporation, All Rights Reserved $ *
#***************************************************************************
#ecpyrght
#
# Index NetBackup client databases

Help ()
{

echo "
usage:	$0
	$0 dirlevels
	$0 dirlevels [client_name]
	$0 dirlevels ALL

where dirlevels is a value from 1 to 9 (default is 9)
"

exit 1
}

# Confirm an action with yes as the default
#
#       confirm prompt_string
#       Returns 0 for yes and 1 for no.

confirm () {
	Valid=1
	while [ $Valid = 1 ]
	do
		echo "\n$1 (y/n) [n] \c"
		read ans
		: ${ans:=n}
		case $ans in
			N*|n*)  return 1 ;;
			Y*|y*)  return 0 ;;
			*)      echo "You have entered an invalid option."
		esac
	done
}


dirlevels=9
clnt="ALL"

# Verify the arguments
if [ "$#" -ge 1 ] ; then
	if [ "$#" = 1 ] ; then
		dirlevels=$1
	elif [ "$#" = 2 ] ; then
		dirlevels=$1
		clnt=$2
	else
		Help
	fi
fi

case "$dirlevels" in
	[1-9] ) ;;
	*) Help ;;
esac

REINDEX=0

if [ "$clnt" = "ALL" ] ; then
	# Indicate that we want all clients indexed.

	if [ -f /usr/openv/netbackup/db/INDEXLEVEL ] ; then
		echo "
The clients are already indexed with a default index level of `cat /usr/openv/netbackup/db/INDEXLEVEL`."
		if confirm "Do you want to recreate the index files for all the clients?"
		then
			/bin/rm -f /usr/openv/netbackup/db/INDEXLEVEL
			REINDEX=1
		else
			exit 2
		fi
	fi

	if [ ! -f /usr/openv/netbackup/db/INDEXLEVEL ] ; then
		echo "
Creating /usr/openv/netbackup/db/INDEXLEVEL with a value of ${dirlevels}.
This file will contain the default index level to use for all new clients."
		echo ${dirlevels} >/usr/openv/netbackup/db/INDEXLEVEL
	fi

elif [ -d /usr/openv/netbackup/db/images/${clnt} ] ; then
	if [ -f /usr/openv/netbackup/db/images/${clnt}/INDEXLEVEL ] ; then
		echo "
Client ${clnt} is already indexed with an index level of `cat /usr/openv/netbackup/db/images/${clnt}/INDEXLEVEL`."
		if confirm "Do you want to recreate the index files for this client?"
		then
			/bin/rm -rf /usr/openv/netbackup/db/images/${clnt}/INDEX
			/bin/rm -f /usr/openv/netbackup/db/images/${clnt}/INDEXLEVEL
		else
			exit 2
		fi
	fi
fi

ls /usr/openv/netbackup/db/images 2>/dev/null |
while read client
do
	if [ -d /usr/openv/netbackup/db/images/${client} ] ; then
		if [ "$clnt" = "ALL" ] ; then
			if [ $REINDEX = 1 ] ; then
				/bin/rm -rf /usr/openv/netbackup/db/images/${client}/INDEX
				/bin/rm -f /usr/openv/netbackup/db/images/${client}/INDEXLEVEL
			fi
		fi

		if [ "$client" = "$clnt" -o "$clnt" = "ALL" ] ; then
			if [ ! -f /usr/openv/netbackup/db/images/${client}/INDEXLEVEL ] ; then
				echo "
Indexing client ${client} to level ${dirlevels}."
				/usr/openv/netbackup/bin/admincmd/bpimage -client ${client} -index ${dirlevels}
			fi
		fi
	fi
done
