#!/usr/bin/env bash
set -e

if [ "$(id -u)" -ne 0 ]; then
  echo "This script must be run as root" >&2
  exit 1
fi

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

if [ -z "$1" ]; then
  echo "Usage: $0 <kernel_pkg_dir>" >&2
  echo "  e.g. $0 kernel6.2  或  $0 /home/user/kernel6.18" >&2
  exit 1
fi

if [[ "$1" = /* ]]; then
  PKG_DIR="$1"
else
  PKG_DIR="$SCRIPT_DIR/$1"
fi

if [ ! -d "$PKG_DIR" ]; then
  echo "Package directory $PKG_DIR does not exist" >&2
  exit 1
fi

cd "$PKG_DIR"

if ! ls ./*.deb >/dev/null 2>&1; then
  echo "No .deb files found in $PKG_DIR" >&2
  exit 1
fi

echo "Using package directory: $PKG_DIR"

# 自动探测内核版本（从 linux-image*.deb 名字中提取）
IMG_DEB=$(ls ./linux-image-*.deb ./linux-image-unsigned-*.deb 2>/dev/null | head -n1 || true)
if [ -z "$IMG_DEB" ]; then
  echo "No linux-image*.deb found in $PKG_DIR, cannot detect kernel version" >&2
  exit 1
fi

BASE_IMG_DEB=$(basename "$IMG_DEB")
KERNEL_VER=$(echo "$BASE_IMG_DEB" | sed -E 's/^linux-image(-unsigned)?-([^_-]+).*$/\2/')

if [ -z "$KERNEL_VER" ]; then
  echo "Failed to detect kernel version from $BASE_IMG_DEB" >&2
  exit 1
fi

echo "Detected kernel version: $KERNEL_VER"

# 安装当前目录下的所有 deb 包
INSTALL_DEBS=()

for f in ./*.deb; do
  if [ -e "$f" ]; then
    INSTALL_DEBS+=("$f")
  fi
done

if [ ${#INSTALL_DEBS[@]} -eq 0 ]; then
  echo "No .deb files found in $PKG_DIR to install" >&2
  exit 1
fi

echo "Installing all debs in $PKG_DIR: ${INSTALL_DEBS[*]}"
export DEBIAN_FRONTEND=noninteractive
apt install -y -q \
  -o Dpkg::Options::="--force-confdef" \
  -o Dpkg::Options::="--force-confold" \
  "${INSTALL_DEBS[@]}"

echo "Installed kernel $KERNEL_VER packages:"
KERNEL_PKGS=$(dpkg -l "linux-image-${KERNEL_VER}*" "linux-modules-${KERNEL_VER}*" "linux-headers-${KERNEL_VER}*" 2>/dev/null | awk '/^ii/ {print $2}')

if [ -z "$KERNEL_PKGS" ]; then
  echo "No installed linux $KERNEL_VER packages found to hold" >&2
  exit 1
fi

# 锁定指定版本的内核包，防止自动升级
apt-mark hold $KERNEL_PKGS

echo "Held packages:"
apt-mark showhold | grep -E "linux-(image|modules|headers)-${KERNEL_VER}" || true