#!/bin/bash

# Examine the eth1 interface - it must always have an IP address to allow the Msm and dependent 
# telephony components to operate.
# If no address is already set for the eth1 interface, assign it any valid value found in the 
# leases file or the default address of 192.168.1.2.

# Lease information is located within file /var/lib/dhcp/dhclient-eth1.leases
# Within the leases file, the IP address, subnet mask, and gateway/router information is stored
# on lines with the following format:
# Note: It is possible for multiple comma-delimited routers to be listed.
#  fixed-address 192.168.1.2;
#  option subnet-mask 255.255.255.0;
#  option routers 192.168.1.1;
#  option routers 192.168.1.1,10.10.11.1;

LEASE_FILE="/var/lib/dhcp/dhclient-eth1.leases"
NNSTARTLOG=/var/log/nn_startup

DEFAULT_IPADDR="192.168.1.2"
DEFAULT_NETMASK="255.255.255.0"
DEFAULT_GATEWAY="192.168.1.1"

IPADDR=
NETMASK=
GATEWAY=

/sbin/ifconfig eth1 | grep "inet addr"
if [ $? -ne 0 ]; then
    # No address found for eth1 interface

    echo `date` " network : eth1 test : no IP address configured on eth1 interface" >> $NNSTARTLOG

    # Examine the dhcp client lease file, if exists, for most recent lease values.
    if [ -e $LEASE_FILE ] && [ ! -z $LEASE_FILE ]; then
        IPADDR=`grep fixed-address $LEASE_FILE | tail -1 | /bin/awk '{print $2}' | /bin/awk --field-separator=';' '{print $1}'`
        NETMASK=`grep subnet-mask $LEASE_FILE | tail -1 | /bin/awk '{print $3}' | /bin/awk --field-separator=';' '{print $1}'`
        GATEWAY=`grep routers $LEASE_FILE | tail -1 | /bin/awk '{print $3}' | /bin/awk --field-separator=',' '{print $1}' | /bin/awk --field-separator=';' '{print $1}'`

        echo `date` " network : eth1 test : lease file values : ipaddr $IPADDR, netmask $NETMASK, gateway $GATEWAY" >> $NNSTARTLOG
    fi

    # If all necessary values are not available, revert all values to default values.
    if [ -z $IPADDR ] || [ -z $NETMASK ] || [ -z $GATEWAY ]; then
        echo `date` " network : eth1 test : reverting to default values : $DEFAULT_IPADDR, $DEFAULT_NETMASK, $DEFAULT_GATEWAY" >> $NNSTARTLOG
        IPADDR=$DEFAULT_IPADDR
        NETMASK=$DEFAULT_NETMASK
        GATEWAY=$DEFAULT_GATEWAY
    fi

    /sbin/ifconfig eth1 $IPADDR netmask $NETMASK up
    if [ $? -ne 0 ]; then
        echo `date` " network : eth1 test : failed to configure eth1 interface with IP $IPADDR, netmask $NETMASK" >> $NNSTARTLOG
        exit
    fi
    /sbin/route add default gw $GATEWAY eth1
    if [ $? -ne 0 ]; then
        echo `date` " network : eth1 test : failed to add default gateway $GATEWAY" >> $NNSTARTLOG
        exit
    fi
fi
