#!/bin/sh
#
# ident "@(#)replaceProp	1.4 07/01/26 SMI"
#
# Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
#

#########################################################
# Usage
#########################################################
usage() {
    cat - << EOF

    Usage: replaceProp -p property_name -v property_value -f property_file

    Updates the value of a property in a property file

	property_name the property to update

	property_value the new value for property_name

	property_file the file that contains the property_name
EOF

    exit 1


}

##########################################################
#
# Replace a specified property name in the file named
# by the 3rd parameter with a specified value.
#
# $1 = the property name
# $2 = the property value
# $3 = full path property file
##########################################################
replace_config_prop() {

    propName=$1
    propValue=$2
    propFile=$3

    PROP_FILE_TMP=/tmp/`basename ${propFile}`.$$

    # fields that contain spaces need to be quoted
    # when replaced in the properties file
    numFields=`echo "$propValue" | awk '{print NF}'`

    if [ -n "$propName" ]; then
	cat ${PROP_FILE} | \
	while read line
	do
	    # Ignore empty lines or lines starting with a comment character.
	    firstChar=`echo $line | awk '{print substr($1, 1, 1)}'`
	    if [ ! -n "${firstChar}" -o "${firstChar}" = "#" ]; then
		echo $line >> $PROP_FILE_TMP
		continue
	    fi

	    # Extract the property name
	    name=`echo $line | awk -F= '{print $1}'`

	    # Found it, so replace with new value.
	    if [ "${name}" = "$propName" ]; then
		# empty value indicates clear the value for the property
		if [ -n "$propValue" ]; then
		    if [ $numFields -gt 1 ]; then
			echo "$propName=\"$propValue\"" >> $PROP_FILE_TMP
		    else
			echo "$propName=$propValue" >> $PROP_FILE_TMP
		    fi
		else
		    echo "$propName=" >> $PROP_FILE_TMP
		fi
		continue
	    fi

	    # Just keep it.
	    echo $line >> $PROP_FILE_TMP
	done

	mv ${PROP_FILE_TMP} ${PROP_FILE}

    fi
} # replace_config_prop



 errCatch=/tmp/replacePropErr.$$
rm -f $errCatch >/dev/null 2>&1
while getopts "p:v:f:" c > $errCatch 2>&1; do
    case $c in
	"p") PROP_NAME=${OPTARG}
	    ;;
	"v") PROP_VALUE=${OPTARG}
	    ;;
	"f") PROP_FILE=${OPTARG}
	    ;;
	esac
done

rm -f $errCatch >/dev/null 2>&1

# make sure we have all 3
if [ -n "${PROP_NAME}" -a  -n "${PROP_FILE}" ]; then
    # update the property
    replace_config_prop ${PROP_NAME} "${PROP_VALUE}" ${PROP_FILE}
else
   exit 1
fi


exit 0


