#!/bin/bash

# This script do the following:
#	Download Memtest

if command -v in.tftpd > /dev/null; then
	source /etc/default/tftpd-hpa
else
	TFTP_DIRECTORY="/srv/tftp"
fi


if ! command -v unzip > /dev/null; then
	apt -y install unzip
fi

### Memtest {{{
MEMTEST_VERSION="5.01"
MEMTEST_URL="http://www.memtest.org/download/${MEMTEST_VERSION}/memtest86+-${MEMTEST_VERSION}.bin.gz"
MEMTEST_INSTALLER_DIR="${TFTP_DIRECTORY}/installer/memtest/"

# (re)Create the installer directory
rm -rf ${MEMTEST_INSTALLER_DIR}
mkdir -p ${MEMTEST_INSTALLER_DIR}
pushd ${MEMTEST_INSTALLER_DIR} > /dev/null

# Config file
CONFIG_PXE="${TFTP_DIRECTORY}/installer/menu.cfg.diag.example"
rm -f ${CONFIG_PXE} && touch ${CONFIG_PXE}

# Download the last version and set simpler name (without the **.bin** extension !)
#wget ${MEMTEST_URL} -O - | gzip -d > memtest86+-${MEMTEST_VERSION}.bin
wget --quiet ${MEMTEST_URL} -O - | gzip -d > memtest86+-${MEMTEST_VERSION}.bin
ln -s memtest86+-${MEMTEST_VERSION}.bin memtest86+

popd > /dev/null

# Config file
/bin/cat >> "${CONFIG_PXE}" << EOF
label memtest
  menu label ^Memory diagnostic tool (Memtest)
  kernel installer/memtest/memtest86+
EOF

### }}}

### Gparted {{{
GPARTED_VERSION="0.27.0-1"
GPARTED_INSTALLER_DIR="${TFTP_DIRECTORY}/installer/gparted"

# (re)Create the installer directory
rm -rf ${GPARTED_INSTALLER_DIR}
mkdir -p ${GPARTED_INSTALLER_DIR}

for ARCH in amd64 i686; do # For available classic architecture
	GPARTED_URL="http://downloads.sourceforge.net/project/gparted/gparted-live-stable/${GPARTED_VERSION}/gparted-live-${GPARTED_VERSION}-${ARCH}.zip"
	GPARTED_TEMP_FILE="gparted-live-${GPARTED_VERSION}-${ARCH}.zip"

	# Create and go into directory
	mkdir -p ${GPARTED_INSTALLER_DIR}/${ARCH}
	pushd ${GPARTED_INSTALLER_DIR}/${ARCH} > /dev/null

	# Download and extract only PXE files
	#wget "${GPARTED_URL}" -O "${GPARTED_TEMP_FILE}"
	wget --quiet "${GPARTED_URL}" -O "${GPARTED_TEMP_FILE}"
	#unzip -j "${GPARTED_TEMP_FILE}" live/filesystem.squashfs live/initrd.img live/vmlinuz -d .
	unzip -q -j "${GPARTED_TEMP_FILE}" live/filesystem.squashfs live/initrd.img live/vmlinuz -d .
	rm -f "${GPARTED_TEMP_FILE}"

	popd > /dev/null

	/bin/cat >> "${CONFIG_PXE}" << EOF
label gpartedlive${ARCH}
  menu label Partiton Manager ${ARCH} (^Gparted)
  kernel installer/gparted/${ARCH}/vmlinuz
  append initrd=installer/gparted/${ARCH}/initrd.img boot=live config components union=overlay username=user noswap noeject ip= vga=788 fetch=tftp://129.20.203.27/installer/gparted/${ARCH}/filesystem.squashfs
EOF

done


### }}}

# Config file
/bin/cat >> "${CONFIG_PXE}" << EOF
label separator
  menu label -----
label mainmenu
  menu label ^Back..
  menu exit
EOF

exit 0
