#!/bin/sh

PREREQ=""

prereqs()
{
    echo "$PREREQ"
}

case $1 in
# get pre-requisites
prereqs)
    prereqs
    exit 0
    ;;
esac

[ ! -x "/sbin/udhcpc" ] && exit

(
cat << 'EOF'
#!/bin/sh
if [ "$1" = "bound" ]; then
    echo DEVICE=\"$interface\" > /tmp/net-$interface.conf
    echo IPV4ADDR=\"$ip\" >> /tmp/net-$interface.conf
    echo IPV4NETMASK=\"$subnet\" >> /tmp/net-$interface.conf
    echo IPV4NETMASKCIDR=\"$mask\" >> /tmp/net-$interface.conf
    echo IPV4GATEWAY=\"$router\" >> /tmp/net-$interface.conf
    echo ROOTSERVER=\"$siaddr\" >> /tmp/net-$interface.conf
    echo ROOTPATH=\"\" >> /tmp/net-$interface.conf
    echo filename=\"$boot_file\" >> /tmp/net-$interface.conf
fi
EOF
) > /tmp/dhcp-script.sh
chmod +x /tmp/dhcp-script.sh
while [ -z "$iplink" ]; do
    iplink=$(ip link show eth0 2> /dev/zero)
    sleep 0.2
done

# Initialize the network card
ip link set eth0 up
sleep 1

# Do the actual DHCP query
while [ -z "$CONFIGURED" ]; do
    udhcpc -n -s /tmp/dhcp-script.sh -i eth0 > /dev/null && CONFIGURED=yes
done

# Write the file that'll then be sourced
mkdir -p /conf
for line in $(cat /tmp/net-eth0.conf); do
    echo export $line >> /conf/param.conf
done
. /conf/param.conf

# Configure the network
ip address add $IPV4ADDR/$IPV4NETMASKCIDR dev $DEVICE
ip route add default via $IPV4GATEWAY
