#!/bin/sh
source "$RUNES_INTERFACE_DIR/RUNES/functions.sh"
[ -f "$RUNES_CONFIG_PATH" ] && source "$RUNES_CONFIG_PATH"
interface=$RUNES_INTERFACE_DIR/$RUNES_RUNE_NAME


eval $(runes_cmdline param_ DHCPd)
# 



eval $(runes_interface ipv4_ LOCAL IPv4Network getNetworkInterfacesList)
# ipv4_Interfaces

eval $(runes_interface tftp_ LOCAL TFTPBoot getNetworkInterfacesList)
# tftp_PXEBootFilePath

# 最初の1つを使う
netdev=$(echo $ipv4_Interfaces | cut -d ' ' -f 1)

if [ -z "$netdev" ];then
	gprintf_failure "No network interface was found."
	exit 1
fi


eval $(runes_interface netdev_ LOCAL IPv4Network getInterfaceInfo $netdev)
# netdev_IPAddress=
# netdev_NetworkAddress=
# netdev_BcastAddress=

range_low=$(echo $netdev_NetworkAddress | cut -d '.' -f 1,2,3).$(expr $(echo $netdev_NetworkAddress | cut -d '.' -f 4) + 1)
range_high=$(echo $netdev_BcastAddress | cut -d '.' -f 1,2,3).$(expr $(echo $netdev_BcastAddress | cut -d '.' -f 4) - 1)


eval $(runes_interface ipv4_ LOCAL IPv4Network getNetworkInfo)
# ipv4_DefaultGateway=
# ipv4_DNS=
rm -rf $interface
mkdir $interface

# FIXME: アドレスプールの大きさの上限を設定する必要がある（DHCPdのメモリが足らない）

echo "\
authoritative ;
max-lease-time 76543;
default-lease-time 76543;
ddns-update-style none;
option space PXE;
option PXE.mtftp-ip               code 1 = ip-address;
option PXE.mtftp-cport            code 2 = unsigned integer 16;
option PXE.mtftp-sport            code 3 = unsigned integer 16;
option PXE.mtftp-tmout            code 4 = unsigned integer 8;
option PXE.mtftp-delay            code 5 = unsigned integer 8;
option PXE.discovery-control      code 6 = unsigned integer 8;
option PXE.discovery-mcast-addr   code 7 = ip-address;

subnet $netdev_NetworkAddress netmask $netdev_NetMask {
	range  $range_low $range_high;
	option subnet-mask $netdev_NetMask;
	option broadcast-address $netdev_BcastAddress;
$(if [ -n "$ipv4_DefaultGateway" ];then echo "	option routers $ipv4_DefaultGateway;";else "	option routers $netdev_IPAddress;"; fi)
	option domain-name \"$viver\";
$([ -n "$ipv4_DNS" ] && echo "	option domain-name-servers $(echo $ipv4_DNS | cut -d ' ' -f 1);")
	#option vendor-class-identifier \"PXEClient\";
	vendor-option-space PXE;
	option PXE.mtftp-ip 0.0.0.0;
$([ -n "$tftp_PXEBootFilePath" ] && echo "	filename \"$tftp_PXEBootFilePath\";")
	next-server $netdev_IPAddress;
}
" > $interface/dhcpd.conf

touch $interface/dhcpd.leases
cp -f ./bin/dhcpd $interface/
$interface/dhcpd -cf $interface/dhcpd.conf -lf $interface/dhcpd.leases # -q



