#!/bin/bash

set -e

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

## Create keys for dynamic DNS update:
CRKEY="$DATADIR/create_ddnskey"
mkdir -p "${target}/$DATADIR"

cat > "${target}/$CRKEY" <<EOF
#!/bin/bash
## create key for ddns
set -e
DIR=\$(pwd)
cd $DATADIR

if ls Kdhcp_updater* 2> /dev/null ; then
    echo "Key exists already, nothing done!"
    exit 1
fi

KEYFILE=\$(dnssec-keygen -a ED25519 -b 128 DHCP_UPDATER).private
KEY=\$(grep 'Key: ' \$KEYFILE | cut -d ' ' -f2)

cat > $DATADIR/ddns.key <<END
key DHCP_UPDATER {
        algorithm HMAC-MD5;
        secret "\$KEY";
};
END

install -o root -g bind -m 0640 $DATADIR/ddns.key /etc/bind/ddns.key
install -o root -g root -m 0640 $DATADIR/ddns.key /etc/dhcp/ddns.key
cd \$DIR
echo "Dynamic DNS update key created and installed."
EOF

chmod ug+x "${target}/$CRKEY"
$ROOTCMD   "$CRKEY"

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

mv -v "$target/etc/dhcp/dhcpd.conf" "$target/etc/dhcp/dhcpd.conf_orig"

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

# FIXME: make this more general for different subnet masks.
PREFIX1=$(echo "$SUBNET" | cut -d "." --fields=1)
PREFIX2=$(echo "$SUBNET" | cut -d "." --fields=2)

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

authoritative;

option domain-name            "intern";
option domain-name-servers    ${NAMESERVER_IPADDR};
option routers                ${GATEWAY};
option ntp-servers            ntp;
option dhcp-max-message-size  2048;

ddns-updates          on;
ddns-update-style     interim;
update-static-leases  on;
use-host-decl-names   on;

include "/etc/dhcp/ddns.key";

zone intern. {
  primary dns;
  key DHCP_UPDATER;
}

zone ${PREFIX2}.${PREFIX1}.in-addr.arpa. {
  primary dns;
  key DHCP_UPDATER;
}

class "PXE-clients" {
   match if substring(option vendor-class-identifier, 0, 9) = "PXEClient";
   ddns-updates    off;
   max-lease-time  120;
   server-name faiserver;
   next-server faiserver;
}

## Submit preseed file location to d-i:
#if substring (option vendor-class-identifier, 0, 3) = "d-i" {
#   filename "http://www/d-i/bullseye/preseed.cfg";
#}

subnet ${SUBNET} netmask ${NETMASK} {
   pool {
      allow unknown-clients;
      max-lease-time 7200;
      range ${RANGE};
      filename "fai/pxelinux.0";
      if not exists host-name {
         option host-name = concat("guest",suffix(binary-to-ascii(10,8,".",suffix(leased-address,1)),2));
         ddns-hostname = config-option host-name;
      }
   }
}

group {
   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
# shellcheck disable=SC2086
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; ddns-hostname workstation${NUMSTR};}" \
	>> "$target/etc/dhcp/dhcpd.conf"
    NUM=$((NUM+1))
done
echo "}" >> "$target/etc/dhcp/dhcpd.conf"
cat >> "$target/etc/dhcp/dhcpd.conf" <<EOF

group {
   filename "fai/pxelinux.0";

EOF
NUM=0
# shellcheck disable=SC2086
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; ddns-hostname diskless${NUMSTR};}" \
	>> "$target/etc/dhcp/dhcpd.conf"
    NUM=$((NUM+1))
done
echo "}" >> "$target/etc/dhcp/dhcpd.conf"
