#!/bin/bash
set -eux
set -o pipefail

# setup tftp directory structure
if [ -f /usr/lib/syslinux/pxelinux.0 ]; then
    # Ubuntu
    pxe_zero="/usr/lib/syslinux/pxelinux.0"
elif [ -f /usr/share/syslinux/pxelinux.0 ]; then
    # Fedora/RHEL
    pxe_zero="/usr/share/syslinux/pxelinux.0"
else
    echo "Failed to find pxelinux.0."
    exit 1
fi

# create tftpboot and cache directories
install -d -m 0755 -o ironic -g ironic /tftpboot/pxelinux.cfg/
install -o ironic -g ironic -m 744 $pxe_zero /tftpboot/pxelinux.0

# for newer syslinux versions we may need to copy in the library
# modules as well (Fedora 21 for example)
if [ -f /usr/share/syslinux/ldlinux.* ]; then
    # Fedora/RHEL
    cp /usr/share/syslinux/ldlinux.* /tftpboot
fi

# Copy in the chain loader for full disk image booting.
syslinux='/usr/share/syslinux'
for f in chain.c32 libcom32.c32 libutil.c32; do
    if [ -f $syslinux/$f ]; then
        cp $syslinux/$f /tftpboot
    fi
done

# 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
    flags           = IPv4
}
EOF

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

# ensure tftpboot dir and all files in it are owned by ironic user
chown ironic:ironic -R /tftpboot
