#!/bin/sh

set -e

# Make sure the copied files are readable by all
umask 022

TFTPBOOT=/var/lib/tftpboot/ltsp
PXECFG=$TFTPBOOT/pxelinux.cfg
LTSPROOT=/opt/ltsp

if [ ! -d $TFTPBOOT ] ; then
    echo "error: Directory $TFTPBOOT is missing.  Unable to continue"
    exit 1
fi

for file in $LTSPROOT/*/boot/vmlinuz* $LTSPROOT/*/boot/initrd.img*; do
    cp -a -v "$file" $TFTPBOOT
done

if [ -f /usr/lib/syslinux/pxelinux.0 ]; then
    cp /usr/lib/syslinux/pxelinux.0 $TFTPBOOT
    if [ ! -d $PXECFG ]; then
        mkdir $PXECFG
    fi
    cat > $PXECFG/default <<EOF
DEFAULT vmlinuz ro initrd=initrd.img quiet splash
EOF
else
    echo "Skipping PXE images.  Install the syslinux package if you need them."
fi

if which mkelf-linux >/dev/null; then
    for kernel in $TFTPBOOT/vmlinuz*; do
        basename=$(basename "$kernel")

        if [ "$basename" = "vmlinuz" ]; then
            initrd=$TFTPBOOT/initrd.img
            nbi=$TFTPBOOT/nbi.img
        else
            version=${basename##vmlinuz-}
            initrd=$TFTPBOOT/initrd.img-$version
            nbi=$TFTPBOOT/nbi.img-$version
        fi

        if [ -f "$initrd" ]; then
            mkelf-linux -o $nbi $kernel $initrd
        else
            mkelf-linux -o $nbi $kernel
        fi
    done
else
    echo "Skipping etherboot images.  Install the mknbi package if you need them."
fi

if which mkvmlinuz >/dev/null; then
  # mkvmlinuz already happens on powerpc as part of the kernel install-
  # so do nothing.
  true
else
    echo "Skipping openfirmware images.  Install the mkvmlinuz package if you need them."
fi

# TODO merge the mkelf-linux and netabootwrap code
if which netabootwrap >/dev/null; then
    for kernel in $TFTPBOOT/vmlinuz*; do
        basename=$(basename "$kernel")

        if [ "$basename" = "vmlinuz" ]; then
            initrd=$TFTPBOOT/initrd.img
            nbi=$TFTPBOOT/nbi.img
        else
            version=${basename##vmlinuz-}
            initrd=$TFTPBOOT/initrd.img-$version
            nbi=$TFTPBOOT/nbi.img-$version
        fi
        # TODO: work around for debian bug #270801
        if [ -f "$initrd" ]; then
            netabootwrap -t $nbi -k $kernel -i $initrd
        else
            netabootwrap -t $nbi -k $kernel
        fi
    done
else
    echo "Skipping netabootwrap images.  Install the aboot package if you need them."
fi

#for file in $TFTPBOOT/*; do
#    found=""
#    for master in $LTSPROOT/*/boot/$(basename "$file"); do
#        if [ -e "$master" ]; then
#            found=1
#            break
#        fi
#    done
#
#    if [ -z "$found" ]; then
#        rm -f "$file"
#    fi
#done
