#!/bin/ksh -p
#
# ident "@(#)utdsupdate.ksh	1.2	06/01/17 SMI"
#
# Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

PROG=$(basename $0)
ETCDIR="/etc/opt/SUNWut"
SRDS_LDAP_CURRENT="$ETCDIR/srds/current"
OPTDIR="/opt/SUNWut/"
SRDS_TEMPLATE_LDAP="$OPTDIR/etc/template/ldap"

TMPDIR=/var/opt/SUNWut/tmp
TMP_CONF_FILE=$TMPDIR/utdsd.acl.conf.$$
TMP_INSERT_FILE=$TMPDIR/utdsd.acl.insert.$$

CONF_FILE="$SRDS_LDAP_CURRENT/utdsd.acl.conf"
BK_EXT="$(date '+%Y_%m_%d_%H:%M:%S')"
CONF_FILE_BK="${CONF_FILE}_${BK_EXT}_$$"

umask 133

#
# prints the usage message.  Arg1 is the output fd (i.e. 1=stdout
# and 2=stderr.
#
Usage() {
	print -u$1 "Usage: $PROG"
}


trap "/bin/rm -f $TMPDIR/utdsd.acl.*.$$" 0 1 2 3 14 15

if [ $# -ne 0 ]; then
	print -u2 "$PROG: extra argument found!"
	Usage 2
	exit 1
fi

# merge the file
if [ ! -f $ETCDIR/utadmin.conf ] || [ ! -f $CONF_FILE ]; then
	# the server is not configured.  No need to merge.
	print -u2 "$PROG: Server not configured.  No update needed."
	exit 0
fi

grep -s "^# SUNWut begin" $CONF_FILE > /dev/null
if [ $? -ne 0 ];then
	# no sun ray entries.  No need to merge.
	print -u2 "$PROG: No Sun Ray entries found in the datastore ACL file.  No update needed."
	exit 0
fi

#
# delete old Sun Ray entries
sed '/^# SUNWut begin/,/^# SUNWut end/d' $CONF_FILE >$TMP_CONF_FILE

#
# delete from the first "access" line to the last line
sed '/^access /,$d' $TMP_CONF_FILE >$TMP_INSERT_FILE

HOSTNAME=`sed -n '/^admin.subtree/s/.* utname=\([^,]*\),.*/\1/p' \
	$ETCDIR/utadmin.conf`
if [ $? -ne 0 ]; then
	print -u2 "$PROG: failed to retrieve subtree info from utadmin.conf file."
	exit 1
fi
ROOTENTRY="o=utdata"
#
# substitute the variables
sed "
    s
@(HOSTNAME)
$HOSTNAME
g
    s
@(ROOTENTRY)
$ROOTENTRY
g
" $SRDS_TEMPLATE_LDAP/utdsd.acl.conf >>$TMP_INSERT_FILE
if [ $? -ne 0 ]; then
	print -u2 "$PROG: failed to merge the ACL file."
	exit 1
fi

#
# only print from the first "access" line to the last line
sed -n '/^access /,$p' $TMP_CONF_FILE >>$TMP_INSERT_FILE
if [ $? -ne 0 ]; then
	print -u2 "$PROG: failed to merge the file"
	exit 1
fi

# only update the file if it's different from the current one
diff -w -i $TMP_INSERT_FILE $CONF_FILE >/dev/null 2>&1
if [ $? -eq 0 ];then
	# no difference
	print -u2 "$PROG: the datastore ACL file is already up-to-date.  No update needed."
	exit 0
fi
print "Updating the ACL configuration file..."

# backup the current config file
cp -p -f $CONF_FILE $CONF_FILE_BK
if [ $? -ne 0 ]; then
	print -u2 "$PROG: failed to backup the current ACL file."
	exit 1
fi

# move the working file to the final destination
mv -f $TMP_INSERT_FILE $CONF_FILE
if [ $? -ne 0 ]; then
	print -u2 "$PROG: failed to update the ACL file."
	diff $CONF_FILE $CONF_FILE_BK
	if [ $? -ne 0 ]; then
		mv -f $CONF_FILE_BK $CONF_FILE
	else
		rm -f $CONF_FILE_BK
	fi
	exit 1
fi
print "... Update completed."
print "A copy of the previous ACL file is store in $CONF_FILE_BK."

exit 0
