#!/usr/bin/env bash
# install-delayed-ifup.sh
# 安装 systemd 定时器，在系统启动后延迟指定时间执行网卡拉起（nmcli/ifup）
# 用法：
#   sudo bash install-delayed-ifup.sh --iface eth1 --delay 60s
# 参数：
#   --iface IFACE   必填，网卡名（如 eth1、eno1、ens33）
#   --delay TIME    选填，延迟时间（默认 60s），支持“60s”、“1min”、或直接数字秒（如 90）

set -euo pipefail

# -------- 参数解析 --------
IFACE=""
DELAY="60s"

print_usage() {
  cat <<EOF
用法: sudo bash $0 --iface IFACE [--delay TIME]
  --iface IFACE   必填，网卡名称（如 eth1、eno1、ens33）
  --delay TIME    可选，延迟时间（默认 60s）。支持：
                  - 60s、1min、2min（systemd 时间格式）
                  - 纯数字（单位秒），如 90，会自动转为 "90s"
示例：
  sudo bash $0 --iface eth1 --delay 60s
  sudo bash $0 --iface eno1 --delay 90
EOF
}

# 简单参数解析
while [[ $# -gt 0 ]]; do
  case "$1" in
    --iface)
      IFACE="${2:-}"
      shift 2
      ;;
    --delay)
      DELAY="${2:-}"
      shift 2
      ;;
    -h|--help)
      print_usage
      exit 0
      ;;
    *)
      echo "未知参数: $1"
      print_usage
      exit 1
      ;;
  esac
done

if [[ -z "$IFACE" ]]; then
  echo "错误：必须指定 --iface"
  print_usage
  exit 1
fi

# 将纯数字 delay 转换为 systemd 时间字符串（秒）
if [[ "$DELAY" =~ ^[0-9]+$ ]]; then
  DELAY="${DELAY}s"
fi

# -------- 权限检查 --------
if [[ $EUID -ne 0 ]]; then
  echo "请使用 root 权限运行：sudo bash $0 --iface $IFACE --delay $DELAY"
  exit 1
fi

echo "准备安装延迟网卡启动：IFACE=$IFACE, DELAY=$DELAY"

# -------- 创建执行脚本 --------
UP_SCRIPT="/usr/local/sbin/iface-up.sh"
cat > "$UP_SCRIPT" <<'EOF'
#!/usr/bin/env bash
# iface-up.sh <IFACE>
# 在系统启动延迟后尝试拉起指定网卡，优先使用 NetworkManager，其次 ifup，最后 ip link
set -euo pipefail

IFACE="${1:-}"
if [[ -z "$IFACE" ]]; then
  echo "Usage: iface-up.sh <IFACE>"
  exit 1
fi

LOG_DIR="/var/log"
LOG_FILE="$LOG_DIR/iface-up-${IFACE}.log"
mkdir -p "$LOG_DIR"

log() {
  echo "[$(date '+%F %T')] $*" | tee -a "$LOG_FILE"
}

log "Starting iface-up for $IFACE"

# 如果有 NetworkManager，优先使用 nmcli
if command -v nmcli >/dev/null 2>&1; then
  log "NetworkManager detected, trying nmcli"

  # 确保设备由 NM 管理（不会报错就好）
  nmcli dev set "$IFACE" managed yes || true

  # 查找绑定到该设备的连接名
  CONN_NAME="$(nmcli -t -f NAME,DEVICE con show | awk -F: -v dev="$IFACE" '$2==dev {print $1; exit}')"

  if [[ -n "$CONN_NAME" ]]; then
    log "Found connection: $CONN_NAME → bringing up"
    nmcli con mod "$CONN_NAME" connection.autoconnect yes || true
    if ! nmcli con up "$CONN_NAME" >> "$LOG_FILE" 2>&1; then
      log "nmcli con up failed, trying nmcli dev connect"
      nmcli dev connect "$IFACE" >> "$LOG_FILE" 2>&1 || true
    fi
  else
    log "No connection bound to $IFACE, trying nmcli dev connect"
    nmcli dev connect "$IFACE" >> "$LOG_FILE" 2>&1 || true
  fi

else
  log "NetworkManager not found, trying ifup"
  # 不同系统 ifup 路径可能不同
  if command -v ifup >/dev/null 2>&1; then
    ifup "$IFACE" >> "$LOG_FILE" 2>&1 || true
  elif [[ -x /sbin/ifup ]]; then
    /sbin/ifup "$IFACE" >> "$LOG_FILE" 2>&1 || true
  elif [[ -x /usr/sbin/ifup ]]; then
    /usr/sbin/ifup "$IFACE" >> "$LOG_FILE" 2>&1 || true
  else
    log "ifup not found"
  fi
fi

# 兜底：直接把链路设置为 up（不保证配置生效，但可尝试）
if ! ip link show "$IFACE" >/dev/null 2>&1; then
  log "Interface $IFACE not present (driver/rename issue?), skipping ip link set up"
else
  log "Setting link up as fallback"
  ip link set "$IFACE" up || true
fi

log "iface-up finished for $IFACE"
exit 0
EOF

chmod +x "$UP_SCRIPT"

# -------- 创建 systemd 模板单元 --------
SERVICE_FILE="/etc/systemd/system/ifup@.service"
TIMER_FILE="/etc/systemd/system/ifup@.timer"

cat > "$SERVICE_FILE" <<EOF
[Unit]
Description=Bring up network interface %i after boot delay
After=network-pre.target NetworkManager.service network.service

[Service]
Type=oneshot
ExecStart=$UP_SCRIPT %i
EOF

cat > "$TIMER_FILE" <<EOF
[Unit]
Description=Run ifup@%i.service after boot delay

[Timer]
OnBootSec=$DELAY
AccuracySec=10s
Unit=ifup@%i.service

[Install]
WantedBy=timers.target
EOF

# -------- 重新加载并启用指定实例的定时器 --------
systemctl daemon-reload
systemctl enable --now "ifup@${IFACE}.timer"

echo "已安装并启动定时器: ifup@${IFACE}.timer (延迟 $DELAY)"
echo "可用命令："
echo "  查看定时器：systemctl list-timers | grep ifup@${IFACE}"
echo "  立即测试服务：systemctl start ifup@${IFACE}.service"
echo "  查看日志：journalctl -u ifup@${IFACE}.service -b"
echo "  详细日志文件：/var/log/iface-up-${IFACE}.log"
echo "  禁用定时器：systemctl disable --now ifup@${IFACE}.timer"
