notice_uboot() {
  echo "Default speed for the RAM in PinePhone is 528 MHz (PC1066 DRAM)."
  echo "If you experience instability or if you want to overclock the RAM,"
  echo "you may select other RAM speed by editing /etc/pinephone/uboot.conf"
  echo "and following the instructions in that file."
  echo
}

flash_uboot() {
  # (Re-)generate the U-Boot boot script and flash the U-Boot image
  pp-uboot-mkscr -q
  pp-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

  # Display the instructions and perform the U-Boot flashing
  notice_uboot
  flash_uboot

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

post_upgrade() {
  # Perform the system cleanups
  remove_extlinux
  update_fstab

  # Display the instructions and perform the U-Boot flashing
  notice_uboot
  flash_uboot
}
