#!/bin/sh

set -e

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

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
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

# TODO merge the mkelf-linux and mkvmlinuz code
if which mkvmlinuz >/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
            mkvmlinuz -o $nbi -k $kernel -i $initrd
        else
            mkvmlinuz -o $nbi -k $kernel
        fi
    done
else
    echo "Skipping openfirmware images.  Install the mkvmlinuz 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
