#!/bin/bash

set -e

if [ -e $target/etc/dhcp/dhcpd.conf_orig ]; then
    exit 0
fi

## Generate the DHCP configuration file 'dhcpd.conf'.
## Use variables from corresponding class/*.var file.

mv $target/etc/dhcp/dhcpd.conf $target/etc/dhcp/dhcpd.conf_orig

if [ -z ${NAMESERVER_IPADDR} ] ; then
    NAMESERVER_IPADDR=$MAINSERVER_IPADDR
fi

cat > $target/etc/dhcp/dhcpd.conf <<EOF
# dhcpd.conf generated by $0

option dhcp-max-message-size 2048;
use-host-decl-names on;

option routers ${GATEWAY};
option domain-name "intern";
option domain-name-servers ${NAMESERVER_IPADDR};
option ntp-servers ntp;

subnet ${SUBNET} netmask ${NETMASK} {
   allow unknown-clients;
   range ${RANGE};
   server-name faiserver;
   next-server faiserver;
   filename "fai/pxelinux.0";
}

group {
   server-name faiserver;
   next-server faiserver;
   filename "fai/pxelinux.0";

   on commit {
        execute("/usr/local/sbin/dhcpd-keytab", host-decl-name);
   }

EOF

PREFIX=`echo $SUBNET | cut -d "." --fields=1,2,3`

NUM=0
for IPADDR in `seq $WS_RANGE` ; do
    NUMSTR=`printf "%02d" $NUM`
    echo "   host workstation${NUMSTR} {hardware ethernet A1:B2:C3:D4:E5:${NUMSTR}; fixed-address $PREFIX.$IPADDR;}" \
	>> $target/etc/dhcp/dhcpd.conf
    NUM=$(($NUM+1))
done
echo "}" >> $target/etc/dhcp/dhcpd.conf
cat >> $target/etc/dhcp/dhcpd.conf <<EOF

group {
   server-name faiserver;
   next-server faiserver;
   filename "fai/pxelinux.0";

EOF
NUM=0
for IPADDR in `seq $DL_RANGE` ; do
    NUMSTR=`printf "%02d" $NUM`
    echo "   host diskless${NUMSTR} {hardware ethernet A1:B2:C3:D4:E5:${NUMSTR}; fixed-address $PREFIX.$IPADDR;}" \
	>> $target/etc/dhcp/dhcpd.conf
    NUM=$(($NUM+1))
done
echo "}" >> $target/etc/dhcp/dhcpd.conf

