#!/bin/bash
set -e

KVER=$(uname -r)
WORKDIR=~/kernelpkg
IMAGEDIR=$WORKDIR/image
HEADERDIR=$WORKDIR/headers

PKGIMAGE="linux-image-${KVER}-bbrx"
PKGHEADER="linux-headers-${KVER}-bbrx"

echo "[*] 内核版本: $KVER"
rm -rf $WORKDIR
mkdir -p $IMAGEDIR/DEBIAN
mkdir -p $IMAGEDIR/boot
mkdir -p $IMAGEDIR/lib/modules
mkdir -p $HEADERDIR/DEBIAN
mkdir -p $HEADERDIR/usr/src

#############################
# 打包 linux-image
#############################
echo "[*] 打包内核..."
cp /boot/vmlinuz-$KVER $IMAGEDIR/boot/
cp /boot/initrd.img-$KVER $IMAGEDIR/boot/
[ -f /boot/config-$KVER ] && cp /boot/config-$KVER $IMAGEDIR/boot/
[ -f /boot/System.map-$KVER ] && cp /boot/System.map-$KVER $IMAGEDIR/boot/
cp -a /lib/modules/$KVER $IMAGEDIR/lib/modules/

cat > $IMAGEDIR/DEBIAN/control <<EOF
Package: $PKGIMAGE
Version: 1.0
Architecture: amd64
Maintainer: you@example.com
Description: Linux kernel $KVER with BBRx congestion control module (includes initrd)
EOF

cat > $IMAGEDIR/DEBIAN/postinst <<'EOF'
#!/bin/bash
set -e
echo "[*] Running update-initramfs..."
update-initramfs -u -k $(uname -r) || true
echo "[*] Running update-grub..."
update-grub || true
exit 0
EOF
chmod 755 $IMAGEDIR/DEBIAN/postinst

dpkg-deb --build $IMAGEDIR
mv ${IMAGEDIR}.deb ~/${PKGIMAGE}_amd64.deb

#############################
# 打包 linux-headers
#############################
echo "[*] 打包内核头文件..."
if [ -d /usr/src/linux-headers-$KVER ]; then
	    cp -a /usr/src/linux-headers-$KVER $HEADERDIR/usr/src/

	        cat > $HEADERDIR/DEBIAN/control <<EOF
Package: $PKGHEADER
Version: 1.0
Architecture: amd64
Maintainer: you@example.com
Description: Linux kernel headers for $KVER (with BBRx support)
EOF

    dpkg-deb --build $HEADERDIR
        mv ${HEADERDIR}.deb ~/${PKGHEADER}_amd64.deb
else
	    echo "[!] 警告: 本机没有 /usr/src/linux-headers-$KVER ，无法打包 headers"
fi

echo "[+] 完成! 生成的包在: "
echo "    ~/${PKGIMAGE}_amd64.deb"
[ -f ~/${PKGHEADER}_amd64.deb ] && echo "    ~/${PKGHEADER}_amd64.deb"

