#!/bin/bash

# This script do the following:
#	Download Clonezilla Stable for amd64 and i686
#	Make a PXE's config file (aka menu.cfg)

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

CZ_INSTALLER_DIR="${TFTP_DIRECTORY}/installer/clonezilla"
CZ_CONFIG_PXE="${CZ_INSTALLER_DIR}/menu.cfg.example"
CZ_VERSION="2.5.0-5"

# Create directories and config file
rm -rf "${CZ_INSTALLER_DIR}"
mkdir -p "${CZ_INSTALLER_DIR}"
touch "${CZ_CONFIG_PXE}"

for ARCH in amd64 i686; do # For available classic architecture
	CZ_URL="https://osdn.jp/dl/clonezilla/clonezilla-live-${CZ_VERSION}-${ARCH}.zip"
	CZ_TEMP_FILE="/tmp/clonezilla-live-${CZ_VERSION}-${ARCH}.zip "

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

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

	popd > /dev/null

	# Config file
	/bin/cat >> "${CZ_CONFIG_PXE}" << EOF
label live${ARCH}
  menu label Clonezilla Live ^${ARCH}
  kernel installer/clonezilla/${ARCH}/vmlinuz
  APPEND initrd=installer/clonezilla/${ARCH}/initrd.img boot=live username=user union=overlay config components quiet noswap edd=on nomodeset nodmraid locales= keyboard-layouts= ocs_live_run="ocs-live-general" ocs_live_extra_param="" ocs_live_batch=no net.ifnames=0 nosplash noprompt fetch=tftp://129.20.203.27/installer/clonezilla/${ARCH}/filesystem.squashfs
EOF

done

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

exit 0
