#!/bin/bash
# read settings from /etc/sysconfig/sysctl and write them to
# /etc/sysctl.conf

. /etc/sysconfig/sysctl 2>/dev/null || exit 0

nofile=
if [ "$1" = "--stdout" ]; then
	shift
	nofile=1
fi
if [ -e "$cfg" -a ! -w "$cfg" ]; then
    nofile=1
fi

cfg=/etc/sysctl.conf

comment_added=''
_doset()
{
    if [ -z "$nofile" -a -z "$comment_added" ]; then
	comment_added=1
	echo
	echo "### converted from /etc/sysconfig/sysctl at `date -R`"
    fi
    echo "$1 = $2"
}

doset()
{
    if [ -z "$nofile" ]; then
	_doset "$@" >> $cfg
    else
	_doset "$@"
    fi
}

isset()
{
    test -z "$nofile" || return 1
    test -e /etc/sysctl.conf || return 1
    grep -q "$1" /etc/sysctl.conf || return 1
}

if ! isset net.ipv4.ip_dynaddr; then
    if [ -n "$IP_DYNIP" -a "$IP_DYNIP" != 'no' ]; then
	if [ "$IP_DYNIP" = 'yes' ]; then
	    IP_DYNIP=7
	fi
	if [ -z "${IP_DYNIP//[0-9]/}" ]; then
	    doset net.ipv4.ip_dynaddr "$IP_DYNIP"
	fi
    fi
fi


if ! isset net.ipv4.tcp_syncookies; then
   if [ "$IP_TCP_SYNCOOKIES" = "yes" ]; then
       doset net.ipv4.tcp_syncookies 1
   fi
fi

if ! isset net.ipv4.ip_forward; then
   if [ "$IP_FORWARD" = "yes" ]; then
       doset net.ipv4.ip_forward 1
   else
       doset net.ipv4.ip_forward 0
   fi
fi

if ! isset net.ipv6.conf.all.forwarding; then
    if [ "$IPV6_FORWARD" = 'yes' ]; then
	doset net.ipv6.conf.all.forwarding 1
    else
	doset net.ipv6.conf.all.forwarding 0
    fi
fi

if ! isset net.ipv6.conf.default.use_tempaddr; then
    if [ -n "$IPV6_PRIVACY"  ]; then
	if [ $IPV6_PRIVACY = yes ]; then
	    IPV6_PRIVACY=2
	fi
	if [ -z "${IPV6_PRIVACY//[0-9]/}" ]; then
	    doset net.ipv6.conf.default.use_tempaddr $IPV6_PRIVACY
	fi
    fi
fi

if ! isset net.ipv6.conf.all.force_mld_version ; then
    if [ -n "$IPV6_MLD_VERSION" -a -z "${IPV6_MLD_VERSION//[0-9]/}" ]; then
	doset net.ipv6.conf.all.force_mld_version $IPV6_MLD_VERSION
    fi
fi

if ! isset kernel.sysrq; then
    if [ "$ENABLE_SYSRQ" = 'yes'  ]; then
	ENABLE_SYSRQ=1
    elif [ "$ENABLE_SYSRQ" = 'no' -o "$ENABLE_SYSRQ" = '176' ]; then
	# 176 is the distro default anyways
	ENABLE_SYSRQ=''
    fi
    if [ -n "$ENABLE_SYSRQ" -a -z "${ENABLE_SYSRQ//[0-9]/}" ]; then
	doset kernel.sysrq "$ENABLE_SYSRQ"
    fi
fi

# sparc only
if [ -e /proc/sys/kernel/stop-a ] && ! isset "kernel.stop-a"; then
    if [ "$ENABLE_STOP_A" = yes ]; then
	doset "kernel.stop-a" 1
    else
	doset "kernel.stop-a" 0
    fi
fi

if ! isset net.ipv4.tcp_ecn; then
    if [ "$DISABLE_ECN" = 'yes' ]; then
	doset net.ipv4.tcp_ecn 0
    fi
fi

if ! isset fs.xfs.probe_dmapi; then
    if [ "$DMAPI_PROBE" = 'yes' ]; then
	doset fs.xfs.probe_dmapi 1
    fi
fi
