#!/bin/sh
#
# ident "@(#)nfs_remove_resource.sh 1.5     00/06/20 SMI"
#
# Copyright (c) 1999-2000 by Sun Microsystems, Inc.
# All rights reserved.
#

#
# cluster/src/cmd/ha-services/nfs/nfs_remove_resource.sh
#
# Called to remove a resource from the HA-NFS state file.
# The caller is assumed to have grabbed the HA-NFS state lock.
# Stdout and stderr of this script are directed to a
# debug file.
#
# The first argument is RGname, second is Rname and the third
# argument is an opcode, which could have values remove or check.
# opcode remove: Removes the resource
# opcode check: Checks to see if the resource is present, exit 0
# if present, exit non-zero if not.
#

HANFS_DIR=/var/run/.hanfs
hanfs_state_file=$HANFS_DIR/nfs.state

if [ $# -ne 3 ]
then
	echo Wrong argument list $*
	exit 1
fi

rg=$1
rs=$2
op=$3

echo RG is $rg R is $rs op is $op


case $op in
	'remove')
		# We might be called even if there is no resource.
		if [ ! -f $hanfs_state_file ]
		then
			echo op remove $hanfs_state_file does not exist
			exit 0
		fi

		# Copy all lines excluding the resource into a tmp file
		# then move the file in one operation

		rm -f $HANFS_DIR/tmp.out
		old_count=`wc -l $hanfs_state_file | awk ' { print $1 }'`
		awk ' $2!=vrs {print $0} ' vrs=$rs < $hanfs_state_file > $HANFS_DIR/tmp.out

		# Double check: It is all right if the resource being removed
		# is not present in the state file, the STOP methods are
		# supposed to be idempotent.
		#
		new_count=`wc -l $HANFS_DIR/tmp.out | awk ' { print $1 }'`

		if [ $old_count -eq $new_count ]
		then
			echo Resource was not present in the state file
			# Return success
			exit 0
		fi
		# Make sure we are removing only one resource.
		old_count=`expr $old_count - 1 `
		if [ $old_count -ne $new_count ]
		then
			echo Old count $old_count new count $new_count
			exit 1	# Leave tmp files around for debugging.
		fi

		# Now rename the file.
		mv /var/run/.hanfs/tmp.out $hanfs_state_file
		rc=$?
		if [ $rc -ne 0 ]
		then
			echo mv command failed with $rc
			exit $rc
		fi

		exit 0	# End of remove case
		;;

	'check')
		# We might be called even if there is no resource.
		if [ ! -f $hanfs_state_file ]
		then
			echo op check $hanfs_state_file does not exist
			exit 1
		fi

		# Check if a given resource is in the state file
		numrs=`awk ' $2==vrs {print $0} ' vrs=$rs < $hanfs_state_file | wc -l`
		if [ $numrs -eq 1 ]
		then
			echo $rs is preset in the state file
			exit 0
		fi
		exit 1
		;;

	*)
		echo Unknown op $op on RG $rg R $rs
		exit 1
		;;
esac

echo Why are we here
exit 1

