#!/bin/sh

# required files from slackware-$VERSION
# kernels/*/bzImage                     ('*' == 'huge.s', 'hugesmp.s', 'speakup.s')
# isolinux/*.txt                        ('*' == 'f2', 'message')
# usb-and-pxe-installers/initrd.img     (12.0)
# isolinux/initrd.img                   (12.1+)
# usb-and-pxe-installers/pxelinux.cfg_default
# /usr/lib/syslinux/pxelinux.0          (package from processed tree)

SLACKWARE=${1/%\//}
TMP=${TMP:-/tmp}

if [ -z "$SLACKWARE" -o ! -d "$SLACKWARE" ] ; then
 echo "Point this script at your toplevel slackware-\$VERSION directory."
 echo
 echo "IE: \"$(basename $0) /pub/mirrors/slackware/slackware-12.1/\""
 exit 1
fi

# clean up old template
rm -rf $TMP/tftpboot/
mkdir -p $TMP/tftpboot/pxelinux.cfg/

cd $SLACKWARE/

# we'll do the following in stages in case the user points this script
# at a non-slackware directory.

if [ ! -z "$(ls kernels/*/bzImage 2> /dev/null)" ] ; then
 cp -p --parents kernels/*/bzImage $TMP/tftpboot/
else
 echo "Kernels ($SLACKWARE/kernels/*/bzImage) not found, aborting."
 exit 1
fi
if [ ! -z "$(ls isolinux/*.txt 2> /dev/null)" ] ; then
 cp -p isolinux/*.txt $TMP/tftpboot/
else
 echo "Installer messages ($SLACKWARE/isolinux/*.txt) not found, aborting."
 exit 1
fi
if [ -e usb-and-pxe-installers/initrd.img ] ; then
 cp -p usb-and-pxe-installers/initrd.img $TMP/tftpboot/
elif [ -e isolinux/initrd.img ] ; then
 cp -p isolinux/initrd.img $TMP/tftpboot/
else
 echo "Initial ramdisk image ($SLACKWARE/*/initrd.img) not found, aborting."
 exit 1
fi
if [ -e usb-and-pxe-installers/pxelinux.cfg_default ] ; then
 cp -p usb-and-pxe-installers/pxelinux.cfg_default $TMP/tftpboot/pxelinux.cfg/default
else
 echo "Installer config ($SLACKWARE/usb-and-pxe-installers/pxelinux.cfg_default) not found, aborting."
 exit 1
fi
if [ ! -z "$(ls */a/syslinux-*.t?z 2> /dev/null)" ] ; then
 # ugly hack for older versions of tar that don't have magic for xz
 case "$(echo */a/syslinux-*.t?z)" in
   *"tbz") COMPRESSOR="bzip2" ;;
   *"tgz") COMPRESSOR="gzip" ;;
   *"tlz") COMPRESSOR="lzma" ;;
   *"txz") COMPRESSOR="xz" ;;
 esac
 mkdir $TMP/$$/
 $COMPRESSOR -dc */a/syslinux-*.t?z | tar xf - -C $TMP/$$/
 cp -p $(find $TMP/$$/ -name 'pxelinux.0') $TMP/tftpboot/
 rm -rf $TMP/$$/
else
 echo "Syslinux package ($SLACKWARE/*/a/syslinux-*.t?z) not found, aborting."
 exit 1
fi

echo "$TMP/tftpboot/ was successfully created & populated."
echo
echo "You may wish to \"chown -R root:root $TMP/tftpboot/\" before"
echo "moving it to your preferred location (typically /tftpboot/)."