#!/bin/sh

set -e

if [ -f /etc/ltsp/ltsp-update-kernels.conf ]; then
    . /etc/ltsp/ltsp-update-kernels.conf
fi

TFTPDIRS=${TFTPDIRS:-"/var/lib/tftpboot /tftpboot"}
BASE=${BASE:-"/opt/ltsp/"}
COPYTFTP=${COPYTFTP:-"true"}
TFTPBOOTDIR=${TFTPBOOTDIR:-"ltsp"}

for TFTPDIR in $TFTPDIRS ; do
    if [ ! -d $TFTPDIR ] ; then
        # skip directory
        continue
    fi

    TFTPBOOT="$TFTPDIR/$TFTPBOOTDIR"

    if [ "$TFTPDIR" = "$BASE" ]; then
        COPYTFTP="false"
        TFTPBOOT="$TFTPDIR"
    fi

    ALL_CHROOTS="$@"
    ALL_CHROOTS=${ALL_CHROOTS:-"$(find $BASE -mindepth 1 -maxdepth 1 -type d)"}
    
    for CHROOT in $ALL_CHROOTS ; do
        if [ -x $CHROOT/bin/true ]; then
            echo "Updating $TFTPDIR directories for chroot: $CHROOT"
            export CHROOT_NAME="$(basename $CHROOT)"
   
            if [ "$COPYTFTP" = "true" ]; then
                mkdir -p $TFTPBOOT/$CHROOT_NAME
                cp -a $CHROOT/boot/. $TFTPBOOT/$CHROOT_NAME/
            fi
        else
            # not a valid chroot
            echo "Skipping invalid chroot: $CHROOT"
        fi
    done
done
