#!/bin/sh

# This example script activates an interface based on the specified
# configuration.
#
# In the interest of keeping the KVP daemon code free of distro specific
# information; the kvp daemon code invokes this external script to configure
# the interface.
#
# The only argument to this script is the configuration file that is to
# be used to configure the interface.
#
# Each Distro is expected to implement this script in a distro specific
# fashion. For instance on Distros that ship with Network Manager enabled,
# this script can be based on the Network Manager APIs for configuring the
# interface.
#
# This example script is based on a RHEL environment.
#
# Here is the format of the ip configuration file:
#
# HWADDR=macaddr
# DEVICE=interface name
# BOOTPROTO=<protocol> (where <protocol> is "dhcp" if DHCP is configured
#                       or "none" if no boot-time protocol should be used)
#
# IPADDR0=ipaddr1
# IPADDR1=ipaddr2
# IPADDRx=ipaddry (where y = x + 1)
#
# NETMASK0=netmask1
# NETMASKx=netmasky (where y = x + 1)
#
# GATEWAY=ipaddr1
# GATEWAYx=ipaddry (where y = x + 1)
#
# DNSx=ipaddrx (where first DNS address is tagged as DNS1 etc)
#
# IPV6 addresses will be tagged as IPV6ADDR, IPV6 gateway will be
# tagged as IPV6_DEFAULTGW and IPV6 NETMASK will be tagged as
# IPV6NETMASK.
#
# The host can specify multiple ipv4 and ipv6 addresses to be
# configured for the interface. Furthermore, the configuration
# needs to be persistent. A subsequent GET call on the interface
# is expected to return the configuration that is set via the SET
# call.
#


##
## XXX This is really hacky. We just whack the existing
## /etc/network/interfaces and also only configure IPv4. This will
## break with multiple network interfaces etc.
##


# Stash away a copy of the config we got
cp $1 /etc/network/hv_config

# Source it
. $1

# Down the interface
ifdown -f $DEVICE

# create a new interfaces file
outf=/etc/network/interfaces
echo "auto lo" > $outf
echo "iface lo inet loopback" >> $outf
echo "" >> $outf
echo "auto $DEVICE" >> $outf

if [  "$BOOTPROTO" = "dhcp" ]; then
    echo "iface $DEVICE inet dhcp" >> $outf
else
    echo "iface $DEVICE inet static" >> $outf
    echo "    address $IPADDR0" >> $outf
    echo "    netmask $NETMASK0" >> $outf
    echo "    gateway $GATEWAY" >> $outf
fi

echo "    hwaddress ether $HWADDR" >> $outf

# create a new resolve.conf file
outf=/etc/resolv.conf
[ -n "$DNS1" ] && echo "nameserver $DNS1" > $outf
[ -n "$DNS2" ] && echo "nameserver $DNS2" >> $outf
[ -n "$DNS3" ] && echo "nameserver $DNS3" >> $outf
[ -n "$DNS4" ] && echo "nameserver $DNS4" >> $outf

# Up the interface
ifup $DEVICE
