#!/bin/bash
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
#
# See the License for the specific language governing permissions and
# limitations under the License.

if [ ${DIB_DEBUG_TRACE:-1} -gt 0 ]; then
    set -x
fi
set -eu
set -o pipefail

SCRIPTDIR=$(dirname $0)

cd /root
git clone git://git.ipxe.org/ipxe.git
cd ipxe/src
if [ -n "${IPXE_GIT_REF:-}" ]; then
  git checkout ${IPXE_GIT_REF}
fi
IPXE_GIT_REF_CURRENT=$(git rev-parse --short HEAD)

make bin/ipxe.lkrn
cp bin/ipxe.lkrn /boot/

cat << EOF >>/etc/grub.d/40_custom
menuentry "iPXE boot ${IPXE_GIT_REF_CURRENT}" {
linux16 /boot/ipxe.lkrn
}
EOF
if [ -s /etc/default/grub ]; then
    sed -i -e 's/^GRUB_TIMEOUT.*/GRUB_TIMEOUT=5/' /etc/default/grub
    sed -i -e 's/^GRUB_DEFAULT.*/GRUB_DEFAULT="iPXE boot"/' /etc/default/grub
fi

# remove all unneeded /boot files
rm -f /boot/vmlinuz*
rm -f /boot/initramfs*
rm -f /boot/initrd.*
rm -f /boot/System.map*
rm -f /boot/config-*
rm -f /boot/symvers-*
rm -rf /boot/grub2/locale
