# Copyright (c) 2012 Tresys Technology LLC, Columbia, Maryland, USA
#
# This software was developed by Tresys Technology LLC
# with U.S. Government sponsorship.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set_sysctl_param() {
# Adds the specified sysctl entry if the key already exists.
#
#  arguments:
#    set_sysctl_param(PARAM,DESIRED)
#      PARAM - Key to search for in sysctl entries.
#      DESIRED - Value that gets assigned to a found sysctl entry.
#
	PARAM=$1
	DESIRED=$2

	MODULE=`/bin/echo "$PARAM"|/bin/sed -e "s/\./\//g"`
	
	if /bin/echo "$PARAM"| /bin/grep -qr "ipv6" /etc/modprobe.d && /bin/grep -qPr "options\s+ipv6\s+disable\=1" /etc/modprobe.d; then
		return 0
	fi

	[ -f "/proc/sys/$MODULE" ] || return 0
	[ -f /etc/sysctl.conf ] || return 1

	if /bin/grep -q "${PARAM}" /etc/sysctl.conf; then
		/sbin/sysctl -q -p
	else
		/bin/echo ""                                 >> /etc/sysctl.conf &&
		/bin/echo "# Added by $(/bin/basename $0) on $(/bin/date -u)" >> /etc/sysctl.conf &&
		/bin/echo "$PARAM = $DESIRED"                       >> /etc/sysctl.conf
	fi

	if ! sysctl -q -w $PARAM=$DESIRED; then
                /bin/echo "sysctl -w $PARAM=$DESIRED failed"
        fi

	. $(dirname $0)/set_general_entry
	safe_add_field "($PARAM\s+=\s+).*" "$DESIRED" /etc/sysctl.conf
}
