#!/bin/sh
# vim:ts=2:sw=2:et
# see also:
# https://kernel-team.pages.debian.net/kernel-handbook/ch-update-hooks.html#s-kernel-hooks

set -e

# Play nice when run under debconf.
exec </dev/null >&2

initrd_version="$1"
initrd_path="$2"

eval set -- "$DEB_MAINT_PARAMS"

case "$1" in
  configure|remove|"")
    ;;
  *)
    exit 0
    ;;
esac

firmware_dst="/boot/firmware"

if ischroot ; then
  true # chroot detected - skip mount point check
elif [ -e /usr/bin/systemd-detect-virt ] && systemd-detect-virt -q ; then
  true # virtualization detected - skip mount point check
elif [ "$(stat -f -c %T "${firmware_dst}")" = "nfs" ]; then
  true
elif ! mountpoint -q "${firmware_dst}" ; then
  echo "raspi-firmware: missing ${firmware_dst}, did you forget to mount it?" >&2
  exit 1
fi

# Default configurations, overridable at /etc/default/raspi-firmware
INITRAMFS=${INITRAMFS:-auto}

# Load user configuration
if [ -r /etc/default/raspi-firmware ] ; then
  . /etc/default/raspi-firmware
fi

flavour="${initrd_version#*-rpi-}"

case $flavour in
  v8|v8-rt|2712|v6|v7|v7l)
    ;;
  *)
    echo "WARNING: Unsupported initramfs version ($initrd_version) - skipping setup"
    echo "NOTE: Manual boot configuration may be required"
    exit 0
    ;;
esac

# Handle initramfs
if [ "$INITRAMFS" = "auto" ]; then
  initrd_dst="$firmware_dst/initramfs$(echo "$flavour" | sed 's/^v//;s/^6//;s/2712/_2712/;s/-/_/;')"
  latest_initrd=$(find /boot -maxdepth 1 -name "initrd.img-*-rpi-$flavour" -print0 | sort -z -V -r | head -z -n1)
  case "$1" in
    configure|"")
      if ! [ -e "$initrd_path" ]; then
        echo "WARNING: $initrd_path not found"
        exit 0
      elif [ "$initrd_path" != "$latest_initrd" ]; then
        exit 0
      fi
      cp -v "$initrd_path" "$initrd_dst"
      ;;
    remove)
      if [ -z "$latest_initrd" ] ; then
        rm -fv "$initrd_dst"
      fi
      ;;
    *)
      exit 1
      ;;
  esac
  sync "$firmware_dst"
fi
