#!/usr/bin/sh
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
# bos720 src/bos/usr/bin/cdat/smit/cdat_add_node.sh 1.3 
#  
# Licensed Materials - Property of IBM 
#  
# COPYRIGHT International Business Machines Corp. 2010,2011 
# All Rights Reserved 
#  
# US Government Users Restricted Rights - Use, duplication or 
# disclosure restricted by GSA ADP Schedule Contract with IBM Corp. 
#  
# IBM_PROLOG_END_TAG 
# @(#)30    1.3  src/bos/usr/bin/cdat/smit/cdat_add_node.sh, cdat, bos720 7/15/11 03:28:23
# This command adds the specified hostname in the specified node file
# If first flag is -i, it also initialize the specified node
#

CAT=cdat.cat
PATH=/bin:/sbin:/usr/bin:/usr/sbin
INIT=""

usage() {
	# should not happen under smit (no internationalization)
	echo "Usage: $0 [-a|-i] -f <node file> <type> [<user>]\n\
		<hostname> -c '<comment>'"
	exit 1
}

[ "$1" != "-a" -a "$1" != "-i" ] && usage
[ "$1" = "-i" ] && INIT="y"
shift

[ $# -lt 6 -o $# -gt 7 -o "$1" != "-f" ] && usage

if [ $# -eq 7 ]
then
	# <user> is present in the parameter list
	echo ${4} | grep '[@:]' 1>/dev/null 2>&1
	if [ $? -eq 0 ]
	then
		dspmsg -s 11 $CAT 6 "Unsupported user name\n"
		if [ -n "$INIT" ]
		then
			# smit exec_mode is "i"
			echo ""
			/usr/bin/dspmsg -s 11 $CAT 3 \
				"Type enter to continue.\n"
			/usr/bin/line
		fi
		exit 2
	fi
	HOST="${5}"
	USERHOST="${4}@${HOST}"
	COMMENT="${7}"
else
	# <user> is not present in the parameter list
	COMMENT="${6}"
	HOST="${4}"
	echo ${HOST} | grep @ 1>/dev/null 2>&1
	if [ $? -eq 0 ]
	then
		# add @ before hostname if there is @ in the hostname
		USERHOST="@${HOST}"
	else
		USERHOST="${HOST}"
	fi
fi

# if file does not already exist and user is not cdat user, create it
# file owner must be cdat user
if [ ! -f "$2" ]
then
	MUSER=`/usr/lib/cdat/smit/cdat_init_values | sed -n 2p \
		| sed -ne 's/:.*$//p'`
	if [ "$USER" != "$MUSER" ]
	then
		su "$MUSER" -c touch "$2"
		[ $? -ne 0 ] && exit 10
	fi
fi

# First grep for no comment, second grep for comments
grep "[:@]${HOST}$" "$2" 1>/dev/null 2>&1
REP=$?
grep "[:@]${HOST}[ 	#]" "$2" 1>/dev/null 2>&1
if [ $? -eq 0 -o $REP -eq 0 ]
then
	dspmsg -s 11 $CAT 5 "Cannot add hostname, already existing\n"
	if [ -n "$INIT" ]
	then
		# smit exec_mode is "i"
		echo ""
		/usr/bin/dspmsg -s 11 $CAT 3 "Type enter to continue.\n"
		/usr/bin/line
	fi
	exit 2
fi

if [ -z "$COMMENT" ]
then
	echo "$3:$USERHOST" >> $2
else
	echo "$3:$USERHOST # $COMMENT" >> $2
fi

if [ -n "$INIT" ]
then
	cdat access -n $3:$USERHOST
	REP=$?
	# smit exec_mode is "i"
	echo ""
	/usr/bin/dspmsg -s 11 $CAT 3 "Type enter to continue.\n"
	/usr/bin/line
	exit $REP
fi
