#!/bin/bash

WOL_IFACES=()
echo
echo "###########################"
for iface in $(ls /sys/class/net/ | grep -vE 'lo|docker|veth|br|bonding_masters'); do
    supports=$(ethtool "$iface" 2>/dev/null | awk -F': ' '/Supports Wake-on/{print $2}' | tr -d '[:space:]')
    if echo "$supports" | grep -q "g"; then
        sudo ethtool -s "$iface" wol g
        WOL_IFACES+=("$iface")
        echo "✅ 已为 $iface 启用 WoL (g)"
    else
        echo "❌ $iface 不支持 WoL (g)"
    fi
done

# -------- 创建 systemd 服务（仅当有至少一个网卡支持 g）--------
if [ ${#WOL_IFACES[@]} -gt 0 ]; then
    # 构建 ExecStart 命令
    exec_start_cmd=""
    for iface in "${WOL_IFACES[@]}"; do
        exec_start_cmd+="/usr/sbin/ethtool -s $iface wol g; "
    done

    sudo tee /etc/systemd/system/wol.service > /dev/null <<EOF
[Unit]
Description=Enable Wake-on-LAN on supported NICs
After=network-online.target

[Service]
Type=oneshot
ExecStart=/bin/bash -c "${exec_start_cmd}"

[Install]
WantedBy=multi-user.target
EOF

    sudo systemctl daemon-reload
    sudo systemctl enable wol.service
    sudo systemctl start wol.service

    echo
    echo "✅ systemd 服务已启用"
else
    echo "⚠ 没有任何网卡支持 WoL"
fi

