#!/bin/bash
# Author: Steven Shiau <steven _at_ nchc org tw>
# License: GPL

# The working dir for the binary hook is the binary/ under working dir (e.g. debian-live/binary/), not in the chroot.
# Put grub2 efi boot loader
# The name server is deconfigured, we have to enable it so the apt-get will work in ocs-gen-grub2-efi-bldr.
# Load DRBL setting and functions
DRBL_SCRIPT_PATH="${DRBL_SCRIPT_PATH:-/usr/share/drbl}"

. $DRBL_SCRIPT_PATH/sbin/drbl-conf-functions

# Part I: EFI-related files
chroot ../chroot mkdir -p /EFI/boot
if [ "$live_efi_boot_loader" = "grub" ]; then
  echo "EFI boot loader is grub. Prepare grub2 EFI boot loader..." 
  # Find the distribution for the chroot environment
  [ -e ../chroot/etc/lsb-release ] && . ../chroot/etc/lsb-release
  if [ "$DISTRIB_ID" = "Ubuntu" ] ;then
    # Ubuntu linux. Use the signed boot loader (shim+grub) so it can be used in uEFI secure boot. shim-signed only exists on amd64 arch.
    if [ -n "$(LC_ALL=C chroot ../chroot apt-cache show shim-signed 2>/dev/null)" ]; then
      # //NOTE// This command is not run in all chroot environment, instead part of its content is run in chroot dir
      echo "Using signed boot loader from Ubuntu..."
      ocs-put-signed-grub2-efi-bldr -c ../chroot ../chroot/EFI/boot
    else
      # Not found (i386 arch), so use normal grub2 efi
      echo "Using unsigned boot loader from Ubuntu..."
      chroot ../chroot /bin/bash ocs-gen-grub2-efi-bldr /EFI/boot
    fi
  else
    # Debian linux
    chroot ../chroot /bin/bash ocs-gen-grub2-efi-bldr /EFI/boot
  fi
  # Clean stale dir EFI if it exists
  # The one created by Clonezilla is in dir EFI.
  rm -rf EFI
  mv ../chroot/EFI ./
elif [ "$live_efi_boot_loader" = "syslinux" ]; then
  # We let ocs-iso and ocs-live-dev to put syslinux's EFI files.
  echo "EFI boot loader is syslinux. Skip running binary hook file $0. The EFI boot loader files will be put by ocs-iso and ocs-live-dev." 
fi

# Part II: misc
# Clean the duplicated vmlinuz-* and initrd-*, we just want vmlinuz and initrd so that the iso file can be smaller.
# For arm64, binary_syslinux of live-build is not run, so there is no hard link (ln) for vmlinuz-* to vmlinuz, and initrd-* to initrd.
# For i386/amd64, binary_syslinux of live-build is run, so there are two files, i.e., ln vmlinuz-4.10.0-38-generic vmlinuz -> so vmlinuz-4.10.0-38-generic and vmlinuz
vmlinuz_no="$(LC_ALL=C find live/ -iname "vmlinuz*" -print 2>/dev/null | wc -l)"
if [ "$vmlinuz_no" -ge 2 ]; then
  # Keep vmlinuz and initrd only.
  rm -f live/vmlinuz-* live/initrd.img-*
elif [ "$vmlinuz_no" -eq 1 ]; then
  # Rename them as vmlinuz and initrd.img
  mv live/vmlinuz-* live/vmlinuz
  mv live/initrd.img-* live/initrd.img
fi

### THE END ###
# DO NOT PUT ANY SCRIPT AFTHER THIS!!!
rm -rf live-binary-hook-dir/
