#!/bin/sh

#-- usage 
usage() { 
	echo "usage : update_search.sh <PATH_2_OLD_SEARCH_SERVER_DIR> <PATH_2_NEW_UPGRADED_SEARCH_SERVER_DIR>" 
	echo ""
	echo "ex : update_search.sh /var/opt/SUNWps/https-`hostname`.`domainname`/portal/ /var/opt/SUNWportal/searchservers/Upgraded/" 
}

#-- failed cmd 
failed() { 
	echo $* 
	exit 1 
}

#-- migration stuff 
migrate() { 	
		SRC=$1; 
		DEST=$2; 
		if ( ( test ! -d $SRC ) || ( test ! -d "$DEST" ) || ( test "$SRC" = "$DEST" ) ) ; then 
			echo "wrong args"
			if ( test ! -d $SRC ) ; then
					echo "src wrong";
			elif ( test ! -d "$DEST" ); then 
				echo "wrong dest" 
			elif ( test "$SRC" = "$DEST" ) ; then 
				echo "$SRC and $DEST are equivalent"
			fi
			usage 
		else 
			echo " copy config files..." 
			if ( test !  -d "$DEST/config" ) ; then 
				failed "missing destination config directory : $DEST/config" 
			elif ( test ! -f "$SRC/config/taxonomy.rdm" ) ; then 
				failed "missing source taxonomy config file : $SRC/config/taxonomy.rdm" 
			elif ( test  ! -f "$SRC/config/filterrules.conf" ) ; then 
				failed "missing source filter.conf : $SRC/config/filterrules.conf "
  			else 
  				cp $SRC/config/taxonomy.rdm $DEST/config 
				cp $SRC/config/filterrules.conf $DEST/config
			fi
			echo " reindexing taxonomy " 
			if ( test ! -x "$DEST/run-cs-cli" ) ; then 
				failed "missing or not executable search cmdline $DEST/run-cs-cli" 
			else
				$DEST/run-cs-cli rdmgr -T -I 
			fi

			# workarround to make search script clean output 
			if ( test ! -L "$SRC/config/SearchLogConfig.properties" ) ; then 
				ln -s $DEST/config/SearchLogConfig.properties $SRC/config 
			fi

			SRC_DBS=`$DEST/run-cs-cli rdmgr -c $SRC/config/search.conf -U -y root|grep "^@database"|grep -v root|cut -d\{ -f2`
			# for each source DB, 
			for DBNAME in $SRC_DBS 
			do	 
				# export persitant data to $DEST/tmp/dbname.p 
				$DEST/run-cs-cli rdmgr -c $SRC/config/search.conf -U -P -y $DBNAME > $DEST/tmp/$DBNAME.p

				# export non-persistant data to $DEST/tmp/dbname.np 
                                $DEST/run-cs-cli rdmgr -c $SRC/config/search.conf -U -N -y $DBNAME > $DEST/tmp/$DBNAME.np

				# import persistant data 
				$DEST/run-cs-cli rdmgr -D -P -y $DBNAME $DEST/tmp/$DBNAME.p

				# import non-persistant data 
				$DEST/run-cs-cli rdmgr -D -N -y $DBNAME $DEST/tmp/$DBNAME.np

				# copy NOVA index (except rd.db) 
				NOVA_INDEXES=`ls $SRC/db/$DBNAME | grep -v "rd.db"` 
				for NOVA_FILE in $NOVA_INDEXES 
				do 
					cp $SRC/db/$DBNAME/$NOVA_FILE $DEST/db/$DBNAME/$NOVA_FILE 
				done 
			done
		fi

		# remove workarround
		rm $SRC/config/SearchLogConfig.properties
}
 
# main   
if (test "$#" != "2" ) ; then 
	echo "wrong number of args"
	usage 
	exit 1
else
	migrate $1 $2
	exit 0
fi
