#!/usr/bin/env bash
# enable-netconsole-gpu.sh —— 在 GPU 机（zywpc / 192.168.31.31）开启 netconsole
# 把内核 printk 实时 UDP 发到 DSH 机（192.168.31.114 / MAC 80:fa:5b:1e:95:61）
#
# 为什么：2026-09-15 整机冻结时屏幕还亮着（内核停止调度），磁盘上没留下死因。
#         netconsole 走内核网络路径，整机卡死时最后几条 printk 仍可能被送到另一台机器。
#
# 用法（GPU 机上，需要 root）：
#     sudo bash enable-netconsole-gpu.sh          # 立即开启（本次运行有效）
#     sudo bash enable-netconsole-gpu.sh --persist # 顺便写重启后自动开启的单元
# 验证：
#     dmesg | grep -i netconsole
#     # DSH 侧：tail -f ~/netconsole-zywpc.log

set -euo pipefail

DEV="${DEV:-enp2s0}"                 # GPU 机网卡
SRC_IP="${SRC_IP:-192.168.31.31}"
DST_IP="${DST_IP:-192.168.31.114}"   # DSH 机（有线口）
DST_MAC="${DST_MAC:-80:fa:5b:1e:95:61}"
PORT="${PORT:-6666}"

[ "$(id -u)" = "0" ] || { echo "需要 root：sudo bash $0" >&2; exit 1; }

modprobe netconsole

# 优先用 configfs（可运行时改；模块参数方式必须重载模块）
if [ -d /sys/kernel/config/netconsole ]; then
  mkdir -p /sys/kernel/config/netconsole/target1
  cd /sys/kernel/config/netconsole/target1
  echo "$DEV"     > dev_name
  echo "$DST_IP"  > remote_ip
  echo "$DST_MAC" > remote_mac
  echo "$PORT"    > local_port
  echo "$PORT"    > remote_port
  echo 1          > enabled
  cd - >/dev/null
  echo "netconsole 已启用（configfs）：$DEV $SRC_IP -> $DST_IP:$PORT"
else
  # 回退：模块参数（需先卸载再加载）
  modprobe -r netconsole 2>/dev/null || true
  modprobe netconsole "netconsole=${PORT}@${SRC_IP}/${DEV},${PORT}@${DST_IP}/${DST_MAC}"
  echo "netconsole 已启用（模块参数）：$DEV $SRC_IP -> $DST_IP:$PORT"
fi

dmesg | grep -i netconsole | tail -3 || true

if [ "${1:-}" = "--persist" ]; then
  echo netconsole >/etc/modules-load.d/netconsole.conf
  cat >/etc/systemd/system/netconsole-target.service <<EOF
[Unit]
Description=Configure netconsole logging target (${DST_IP}:${PORT})
After=network-online.target
Wants=network-online.target

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/bin/bash -c 'modprobe netconsole; mkdir -p /sys/kernel/config/netconsole/target1; cd /sys/kernel/config/netconsole/target1; echo ${DEV} > dev_name; echo ${DST_IP} > remote_ip; echo ${DST_MAC} > remote_mac; echo ${PORT} > local_port; echo ${PORT} > remote_port; echo 1 > enabled'

[Install]
WantedBy=multi-user.target
EOF
  systemctl daemon-reload
  systemctl enable --now netconsole-target.service
  echo "已写入并启用 netconsole-target.service（重启后自动生效）"
fi
