disable_cma() {
  if [[ -f /boot/config.txt && $(grep '^cma' /boot/config.txt) != '' ]]; then
    cat <<END

>>> You appear to have dynamic memory (CMA) enabled, which is currently broken
    in newer kernels and will cause many issues if left enabled. Disabling that
    for you now.

END
    sed -i 's/^cma_/#cma_/g' /boot/config.txt
  fi
}

correct_fstab() {
  # starting with v5.10.y, fstab requires a padded zero in the path to /boot
  if [[ -f /etc/fstab ]]; then
    if grep -q mmcblk1p1 /etc/fstab; then
      sed -i 's/mmcblk1p1/mmcblk0p1/' /etc/fstab
    fi
  fi
}

pikvm_move_pacsave() {
  for name in config cmdline; do
    if [ -f /boot/$name.txt.pacsave ]; then
      mv /boot/$name.txt.pacsave /boot/$name.txt
      echo ">>> PiKVM: /boot/$name.txt.pacsave moved to /boot/$name.txt"
    fi
  done
}

pikvm_remove_cma() {
  # It's also broken and leads to hang up after "rainbow" sreen
  cat /boot/cmdline.txt \
      | xargs printf "%s\n" \
      | grep -v '^cma=' \
      | paste -sd ' ' - \
    > /boot/cmdline.txt.kernel-new
  mv /boot/cmdline.txt.kernel-new /boot/cmdline.txt
}

post_install () {
  post_upgrade
}

post_upgrade() {
  correct_fstab
  disable_cma
  pikvm_move_pacsave
  pikvm_remove_cma

  if grep "^[^#]*[[:space:]]/boot" etc/fstab 2>&1 >/dev/null; then
    if ! grep "[[:space:]]/boot" etc/mtab 2>&1 >/dev/null; then
      cat <<END

>>> WARNING: /boot appears to be a separate partition but is not mounted.
    You probably just broke your system. Congratulations.

END
    fi
  fi
}

post_remove() {
  rm -f boot/initramfs-linux.img
}
