#!/bin/sh

# build_kernel_deb.sh
# 2023-08-19
# by Gernot Walzl

# This script builds a Debian package of the Linux kernel.
# https://wiki.debian.org/BuildADebianKernelPackage
# https://kernel.org/category/signatures.html
# https://www.kernel.org/doc/makehelp.txt

VERSION=${VERSION:-'6.4.11'}
SOURCE="linux-${VERSION}.tar.xz"
DOWNLOAD="https://cdn.kernel.org/pub/linux/kernel/v6.x/${SOURCE}"
SIGNATURE="linux-${VERSION}.tar.sign"
SIGNATURE_DOWNLOAD="https://cdn.kernel.org/pub/linux/kernel/v6.x/${SIGNATURE}"
GPG_KEY="gregkh@kernel.org"
if [ -z "$OLDCONFIG" ]; then
  OLDCONFIG=$(find /boot -maxdepth 1 -type f -name 'config*' | sort | tail -n 1)
fi


# set initial variables
CWD=$(pwd)
TMP=${TMP:-/tmp}

# exit on error
set -e


download () {
  if [ ! -f "$CWD/$SOURCE" ]; then
    wget -O "$CWD/$SOURCE" "$DOWNLOAD" || exit 1
  fi
  if [ ! -f "$CWD/$SIGNATURE" ]; then
    wget -O "$CWD/$SIGNATURE" "$SIGNATURE_DOWNLOAD" || exit 1
  fi

  # import gpg key
  if ! gpg --list-keys "$GPG_KEY"; then
    gpg --locate-keys "$GPG_KEY"
  fi

  # decompress
  cd "$TMP" || exit 1
  xzcat "$CWD/$SOURCE" > "linux-${VERSION}.tar"
  cat "$CWD/$SIGNATURE" > "$SIGNATURE"

  # check signature
  gpg --verify "$SIGNATURE"

  echo ""
  echo "Press Enter to continue."
  read CONTINUE

  # extract
  tar xvf "linux-${VERSION}.tar" || exit 1

  # clean up
  rm "linux-${VERSION}.tar"
  rm "$SIGNATURE"
}


install_build_deps () {
  sudo apt-get build-dep linux
}


build_deb_pkg () {
  cd "${TMP}/linux-${VERSION}" || exit 1

  # print notice
  echo ""
  echo "Building kernel $VERSION"
  echo "with old config from $OLDCONFIG"
  echo ""
  echo "Press Enter to continue."
  read CONTINUE

  # build the kernel
  cp "$OLDCONFIG" .config
  make olddefconfig
  make -j "$(nproc)" bindeb-pkg
}


download
install_build_deps
build_deb_pkg