#!/bin/sh -efu

daemons="$daemons ipxe"
packages="$packages xinetd tftpd dhcp-server ipxe-bootimgs"
start_services="$start_services xinetd dhcpd"

ipxe_setup()
{
	echo
	echo "iPXE-server setup (xinetd, tftpd, dhcpd)..."
	sed -i -E 's/^(\s+only_from.*)$/#\1/' /etc/xinetd.conf
	cat >/etc/sysconfig/xinetd <<-EOF
	# Add extra options here
	EXTRAOPTIONS='-remlock'
	EOF
	cat >/etc/xinetd.d/tftp <<-EOF
	# default: off
	# description: The tftp server serves files using the trivial file transfer \
	#	protocol.  The tftp protocol is often used to boot diskless \
	#	workstations, download configuration files to network-aware printers, \
	#	and to start the installation process for some operating systems.
	service tftp
	{
	  disable	= no
	  socket_type	= dgram
	  protocol	= udp
	  wait		= yes
	  user		= root
	  server	= /usr/sbin/in.tftpd
	  server_args	= -4 -a $server -u tftp -s /srv/boot -m /etc/tftpd.map
	}
	EOF
	cat >/etc/tftpd.map <<-EOF
	# Convert backslashes to slashes
	rg \\\\ /
	EOF
	cat > /etc/dhcp/dhcpd.conf <<-EOF
	# Auto-generated by post-install script
	# See dhcpd.conf(5) for further configuration

	authoritative;
	ddns-update-style none;
	ddns-domainname "$domain";

	option space altlinux;
	option altlinux.keydata code 2 = string;
	vendor-option-space altlinux;

	option arch code 93 = unsigned integer 16;

	option space ipxe;
	option ipxe.no-pxedhcp code 176 = unsigned integer 8;

	subnet $subnet.0 netmask 255.255.255.0 {
	  option nis-domain		"$domain";
	  option domain-name		"$domain";
	  option routers		$gateway;
	  option broadcast-address	$subnet.255;
	  option subnet-mask		255.255.255.0;

	  default-lease-time		1800;
	  max-lease-time		3600;

	  option ipxe.no-pxedhcp	1;

	  if exists user-class and option user-class = "iPXE" {
	     filename "http://$server/boot/script.ipxe";
	  } elsif option arch = encode-int(16, 16) {
	     option vendor-class-identifier "HTTPClient";
	     filename "http://$server/boot/ipxe-x86_64.efi";
	  } elsif substring (option vendor-class-identifier, 0, 9) = "PXEClient" {
	     next-server		$server;

	     if option arch = 00:06 {		# EFI IA32
	        filename "ipxe-i386.efi";
	     } elsif option arch = 00:07 {	# EFI Byte Code
	        filename "ipxe-x86_64.efi";
	     } elsif option arch = 00:09 {	# EFI x86-64
	        filename "ipxe-x86_64.efi";
	     } elsif option arch = 00:00 {	# Legacy BIOS
	        filename "undionly.kpxe";
	     }
	  }

	  pool {
	     range $subnet.50 $subnet.250;
	  }
	}
	EOF
	echo "DHCPDARGS='$iface'" >/etc/sysconfig/dhcpd
	ln -snf /usr/share/ipxe/ipxe-i386.efi /srv/boot/
	ln -snf /usr/share/ipxe/undionly.kpxe /srv/boot/
	ln -snf /usr/share/ipxe/ipxe-x86_64.efi /srv/boot/
}

