#!/bin/bash

_BASE_DIR_=$(readlink -f $(dirname "${BASH_SOURCE[0]}"))
# load config
_CONFIG_FILE_=${_BASE_DIR_}/config

. ${_CONFIG_FILE_}

for _DIR_ in ${_MK_DIRS_[*]} ; do
  mkdir "${_DIR_}" || exit 1
done

7z -y x "${_ISO_SRC_PATH_}" -o"${_EXTRACT_DIR_}"

for _ITEM_ in ${_MV_ITEMS_[*]} ; do
  mv -i "${_EXTRACT_DIR_}/"${_ITEM_} "${_REMASTER_DIR_}/." || exit 1
done

mkdir -m 0700 "${_REMASTER_DIR_}/${_SETUP_DIR_}"

_SETUP_DIR_SRC_="${_BASE_DIR_}/${_SETUP_DIR_}"
_SETUP_DIR_DEST_="${_REMASTER_DIR_}/${_SETUP_DIR_}"

cp -ip "${_SETUP_DIR_SRC_}/authorized_keys" "${_SETUP_DIR_DEST_}/."
cp -ip "${_SETUP_DIR_SRC_}/late_command.sh" "${_SETUP_DIR_DEST_}/."
cp -ip "${_SETUP_DIR_SRC_}/preseed-vda.cfg" "${_SETUP_DIR_DEST_}/preseed.cfg"

# change uefi menu
sed 's@^\(set theme=/boot.*\)$@\1\nset timeout=5\nmenuentry '"'Automated Install'"' {\n    set background_color=black\n    linux    /install.amd/vmlinuz net.ifnames=0 biosdevname=0 auto=true priority=critical vga=788 hostname='"${_HOSTNAME_}"' file='"${_FILE_BASE_}"'/preseed.cfg\n    initrd   /install.amd/initrd.gz\n}@' -i "${_REMASTER_DIR_}/boot/grub/grub.cfg"

# change bios menu
sed 's@label install@timeout 50\ndefault installai\nlabel installai@;s@Install$@Automated Install\n\tmenu default@g;s@ --- quiet@ net.ifnames=0 biosdevname=0 auto=true priority=critical hostname='"${_HOSTNAME_}"' file='"${_FILE_BASE_}"'/preseed.cfg@' "${_REMASTER_DIR_}/isolinux/txt.cfg" > "${_REMASTER_DIR_}/isolinux/ai.cfg" && \
  sed '/default installgui/d;/^[[:space:]]\+menu default$/d' -i "${_REMASTER_DIR_}/isolinux/gtk.cfg" && \
  sed 's/^\(include gtk.cfg\)/include ai.cfg\n\1/;/spk.*.cfg/d' -i "${_REMASTER_DIR_}/isolinux/menu.cfg"

