#!/bin/sh
#
# @(#)mcp_propagate.sh	1.10 01/02/14
# Copyright (c) 02/14/01 Sun Microsystems, Inc. All Rights Reserved.
#

LOCAL_BASE=`expr "$INTERFACE_PATH" : '\([^:]*\)'`
LOCAL_BASE=`dirname $LOCAL_BASE`

#
# remove MCP module file
#
if [ -f "$LOCAL_BASE/cfg/base-modules-d.dat.MCP" ] ; then
    rm "$LOCAL_BASE/cfg/base-modules-d.dat.MCP"
fi

TMP_LOG_DIR="/tmp/sunmclog/"
mkdir -m 777 -p $TMP_LOG_DIR

LOGFILE="$TMP_LOG_DIR"`basename $0`.$$.log

#
# initialize the log file
#
echo $0 called at `date` with args: $* >$LOGFILE

#
# check expanded argument list
#
if [ $# -ne 1 ]
then
    echo "Usage: $0 id,url,parcel,propagate,load,parameters,security,schedule" >&2
    exit 1
fi

#
# expand first argument into its three components
#
OLDIFS=$IFS
IFS=,
set $1
IFS=$OLDIFS

#
# check expanded argument list
#
if [ $# -ne 8 ]
then
    echo "Usage: $0 id,url,parcel,propagate,load,parameters,security,schedule" >&2
    exit 1
fi

echo "$0 $1 $2 $3 $4 $5 $6 $7 $8" >> $LOGFILE

ID=$1
URL=$2
PARCEL=$3
PARAM_PROPAGATE=$4  # 0 = always, 1 = if not loaded
PARAM_LOAD=$5	    # 0 = always, 1 = as is
PARAM_PARAMETERS=$6 # 0 = reference, 1 = target
PARAM_SECURITY=$7   # 0 = reference, 1 = target
PARAM_SCHEDULE=$8   # 0 = reference, 1 = target

#
# perform the get
#
RESULT=`es-mcp-get $ID $URL $LOCAL_BASE $PARCEL $PARAM_PROPAGATE 2>>$LOGFILE`

#
# check status
#
STATUS=$?
if [ $STATUS -ne 0 ]
then
    if [ $STATUS -ne 255 ]
    then
	#
	# failure - log error and exit, leaving log file for perusal
	#
	echo $RESULT >>$LOGFILE
	echo "error: es-mcp-get failed - see $LOGFILE for details" >&2
	echo "error: es-mcp-get failed - see $LOGFILE for details" >> $LOGFILE
	echo "failure"
	exit 2
    else
	echo "success"
	exit 0
    fi
fi

#
# success - merge any MCP DAT files with the originals
#
for module in `/usr/bin/nawk '{ print $1 }' $LOCAL_BASE/cfg/base-modules-d.dat.MCP`
do
    DATFILE="$LOCAL_BASE/cfg/"$module".dat"
    MCPFILE=$DATFILE".MCP"
    TMPFILE=$DATFILE".TMP"

    #
    # ensure DAT file exists
    #
    touch $DATFILE

    echo "merging $MCPFILE into $DATFILE" >> $LOGFILE

    #
    # remove everything but security info from the dat file
    #
    if [ "$PARAM_SECURITY" = "1" ] ; then # Use the target security info
	/usr/bin/egrep '(^value:.*=)|(value:ackName *=)|(= *{[ 	]*$)|(^[ 	]*}[ 	]*$)' $DATFILE > $TMPFILE
    else
	/usr/bin/egrep '(^value:.*=)' $MCPFILE > $TMPFILE
	/usr/bin/egrep '(value:ackName *=)|(= *{[ 	]*$)|(^[ 	]*}[ 	]*$)' $DATFILE >> $TMPFILE
    fi

    #
    # append the MCP dat file content
    #
    cat $MCPFILE | /usr/bin/grep -v "^value:" >> $TMPFILE

    #
    # overwrite original
    #
    mv $TMPFILE $DATFILE
done

#
# clean up log file and exit
#
rm -f $LOGFILE
echo "success"
exit 0
