#!/bin/bash
set -eux

install-packages syslinux tftpd-hpa xinetd

mkdir -p /tftpboot/pxelinux.cfg/
if [ -f /usr/lib/syslinux/pxelinux.0 ]; then
    cp /usr/lib/syslinux/pxelinux.0 /tftpboot/ # Ubuntu
elif [ -f /usr/share/syslinux/pxelinux.0 ]; then
    cp /usr/share/syslinux/pxelinux.0 /tftpboot/ # Fedora/RHEL
else
    echo "Failed to find pxelinux.0."
    exit 1
fi

# Disable the tftp-hpa upstart job, we're using xinetd
[ -f /etc/init/tftpd-hpa.conf ] && echo "manual" > /etc/init/tftpd-hpa.override

# Disable the tftpd-hpa SysV script for the same reason
[ -f /etc/init.d/tftpd-hpa ] && update-rc.d -f tftpd-hpa disable

cat > /etc/xinetd.d/tftp << EOF
service tftp
{
  protocol        = udp
  port            = 69
  socket_type     = dgram
  wait            = yes
  user            = root
  server          = /usr/sbin/in.tftpd
  server_args     = --map-file /tftpboot/map-file /tftpboot
  disable         = no
}
EOF

# Adds support for tftp requests that don't include the directory name.
echo 'r ^([^/]) /tftpboot/\1' > /tftpboot/map-file

os-svc-enable -n xinetd
