#!/bin/sh

# keep_kernel-4.14.rpi.sh
# 2020-03-10
# by Gernot Walzl

# Prevents all kernel related upgrades by setting them on hold
# and installs the latest stable kernel from branch 4.14.

RPI_KERNEL_HEADERS=${RPI_KERNEL_HEADERS:-'no'}

RPI_KERNEL_PKGS="raspberrypi-bootloader raspberrypi-kernel libraspberrypi0 libraspberrypi-bin libraspberrypi-dev libraspberrypi-doc"
if [ "$RPI_KERNEL_HEADERS" = "yes" ]; then
  RPI_KERNEL_PKGS="$RPI_KERNEL_PKGS raspberrypi-kernel-headers"
fi
RPI_KERNEL_4_14_VER="20190401"
ARCHIVE_URL="http://archive.raspberrypi.org/debian/pool/main/r/raspberrypi-firmware/"
FIRMWARE_REV="45a2e771e7272781e62ae92322734c2b90e0268a"

set -e

check_version_codename () {
  if ! grep -q 'Raspbian GNU/Linux 9 (stretch)' /etc/os-release; then
    echo
    echo 'ERROR: Raspbian 9 (stretch) required'
    echo
    exit 1
  fi
}

mark_rpi_kernel_pkgs () {
  if [ "$1" != "hold" -a "$1" != "unhold" ]; then
    return 1
  fi
  local CMD="apt-mark $1 $RPI_KERNEL_PKGS"
  echo
  echo "$CMD"
  echo
  $CMD
}

install_latest_rpi_kernel_pkgs () {
  CMD="apt-get --reinstall install $RPI_KERNEL_PKGS"
  echo
  echo "$CMD"
  echo
  $CMD
}

install_rpi_kernel_4_14_pkgs () {
  mkdir -p "${RPI_KERNEL_4_14_VER}"
  cd "${RPI_KERNEL_4_14_VER}"
  for PKG in $RPI_KERNEL_PKGS; do
    local DEBFILE="${PKG}_1.${RPI_KERNEL_4_14_VER}-1_armhf.deb"
    if [ ! -f "$DEBFILE" ]; then
      wget "${ARCHIVE_URL}${DEBFILE}" -O "${DEBFILE}"
    fi
  done
  echo
  echo 'Installing kernel packages:'
  echo
  for PKG in $RPI_KERNEL_PKGS; do
    local DEBFILE="${PKG}_1.${RPI_KERNEL_4_14_VER}-1_armhf.deb"
    dpkg -i "${DEBFILE}"
  done
}

install_stable_kernel () {
  echo
  echo "rpi-update"
  echo
  rm /boot/.firmware_revision
  BRANCH='stable' rpi-update "$FIRMWARE_REV"
}

need_reboot () {
  sync
  echo
  echo "A reboot is needed to activate the new firmware"
}

check_version_codename
case "$1" in
  'undo')
    mark_rpi_kernel_pkgs 'unhold'
    install_latest_rpi_kernel_pkgs
    ;;
  'rpi-update')
    install_stable_kernel
    mark_rpi_kernel_pkgs 'hold'
    ;;
  *)
    install_rpi_kernel_4_14_pkgs
    mark_rpi_kernel_pkgs 'hold'
    ;;
esac
need_reboot