flash_uboot() {
  # (Re-)generate the U-Boot boot script and flash the U-Boot image
  ppp-uboot-mkscr -q
  ppp-uboot-flash
}

remove_extlinux() {
  # Remove an unused directory, if it's present
  if [[ -e /boot/extlinux ]]; then
    echo "Removing unused /boot/extlinux directory..."
    rm -rf /boot/extlinux
  fi
}

update_fstab() {
  local BOOT_OPTIONS="defaults,noexec,nodev,showexec"

  # Ensure updated mount options for /boot in /etc/fstab, if the /boot
  # partition entry is present and it is using vfat filesystem
  if [[ -f /etc/fstab ]] && \
     grep -q -E "[[:blank:]]+/boot[[:blank:]]+vfat[[:blank:]]+" /etc/fstab && \
     ! grep -q -E "[[:blank:]]+/boot[[:blank:]]+vfat[[:blank:]]+${BOOT_OPTIONS}[[:blank:]]+" /etc/fstab; then
    echo "Updating mount options for /boot in /etc/fstab..."
    sed -i -e "s#\([ \t]\+\)\(/boot\)\([ \t]\+\)\([^ \t]\+\)\([ \t]\+\)\([^ \t]\+\)\(.*\)\$#\1\2\3\4\5${BOOT_OPTIONS}\7#g" \
      /etc/fstab
  fi
}

post_install() {
  # Perform the system cleanups
  remove_extlinux
  update_fstab

  # Perform the U-Boot flashing
  flash_uboot

  # The service will be executed only once, it disables itself
  systemctl enable ppp-prepare-fstab.service
}

post_upgrade() {
  # Perform the system cleanups
  remove_extlinux
  update_fstab

  # Perform the U-Boot flashing
  flash_uboot
}
