#!/bin/sh
# This is not a standalone shell script;
# it just provides functions to network scripts that source it.

source_config ()
{
    DEVNAME=`echo "${CONFIG##*/}" | sed 's/^ifcfg-//g'`

    if basename $CONFIG |grep -qs '[^g]-'; then
	PARENTCONFIG=`echo $CONFIG | sed 's/-[^-]*$//g'`
	PARENTDEVNAME=`basename $PARENTCONFIG | sed 's/^ifcfg-//g'`
	[ -f $PARENTCONFIG ] || {
	    echo "Missing config file $PARENTCONFIG." >&2
	    exit 1
	}
	. $PARENTCONFIG
    fi
    . $CONFIG
}

toggle_value()
{
	if [ -z "$2" ]; then
		echo ''
	elif [ "$2" = "yes"  -o "$2" = "YES" ] ; then
		echo "$1"
	elif [ "$2" = "no"  -o "$2" = "NO" ] ; then
		echo "-$1"
	else
		echo ''
	fi
}
 
ip_link_flag()
{
	case "$2" in
		[Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn])
			echo "$1" on
		;;
		[Nn][Oo]|[Ff][Aa][Ll][Ss][Ee]|[Oo][Ff][Ff])
			echo "$1" off
		;;
		*)
		;;
	esac
}
 
do_netreport ()
{
  # Notify programs that have requested notification
  (
	cd /var/run/netreport || exit
	for i in *; do
		if [ -f "$i" -a -d "/proc/$i" ]; then
			kill -SIGIO "$i" >/dev/null 2>&1
		else
			rm -f "$i"
		fi
	done
  )
}

need_hostname()
{
	local hostname="`hostname`"
	if [ "$hostname" = '(none)' -o "$hostname" = 'localhost' -o "$hostname" = 'localhost.localdomain' ]; then
		NEEDHOSTNAME=yes
	else
		unset NEEDHOSTNAME
	fi
}

set_hostname()
{
    hostname $1
    if ! fgrep -qs search /etc/resolv.conf; then
	domain=`dnsdomainname`
	[ -z "$domain" ] || echo "search $domain" >>/etc/resolv.conf
    fi
}

check_device_down ()
{
    if LC_ALL= LANG= ifconfig ${DEVICE} 2>/dev/null |fgrep -qs ' UP '; then
	retcode=1
    else
	retcode=0
    fi
    return $retcode
}

check_default_route ()
{
    return `/sbin/route -n|gawk 'BEGIN{r=1} $3=="0.0.0.0" && $4=="UG" {r=0} END{print r}'`
}

find_gateway_dev ()
{
    . /etc/sysconfig/network
    if [ -n "$GATEWAY" -a "$GATEWAY" != "none" ] ; then
        export GATEWAY
        networks=`/sbin/route -n|awk '{print $1, ENVIRON["GATEWAY"],$3,$8}'|awk '{system("ipcalc --silent --network "$2" "$3" 2>/dev/null")}'|sed s^NETWORK=^^g`
        for net in $networks; do
            dev=`/sbin/route -n|grep ^$net|awk '{print $NF}'`
            if [ "$dev" != "" ] ; then
                GATEWAYDEV=$dev
            fi
        done
    fi
}

add_default_route ()
{
    . /etc/sysconfig/network
    find_gateway_dev
    if [ -n "$GATEWAY" -a "$GATEWAY" != "none" -a -n "$GATEWAYDEV" ]; then
        if ! check_device_down; then
            if [ "$GATEWAY" = "0.0.0.0" ]; then
                /sbin/route add default ${GATEWAYDEV}
            else
                /sbin/route add default gw ${GATEWAY} ${GATEWAYDEV}
            fi
        fi
    fi
}

check_eth_link ()
{
	local IFSTATUS
	local res
	IFSTATUS=/sbin/ifplugstatus
	[ -x $IFSTATUS ] || return 0
	# run ifplugstatus only for eth
	[ "${DEVICE/eth*/eth}" = "eth" ] || return 0
	$IFSTATUS -q $DEVICE 
	res=$?
	[ "$res" = 3 ] && return 1
	return 0
}
