#!/usr/bin/env bash
set -euo pipefail

CONF_DIR="/etc/pve/qemu-server"
ts="$(date +%Y%m%d%H%M%S)"

echo ">>> 遍历读取 $CONF_DIR/*.conf"
echo ">>> 修复：netX 行里重复 link_down（>1）/ 或出现 link_down=1"
echo ">>> 目标：去重并确保最终只有一个 link_down=0"
echo

shopt -s nullglob
confs=("$CONF_DIR"/*.conf)
if (( ${#confs[@]} == 0 )); then
  echo "ERROR: $CONF_DIR 下没有 .conf 文件"
  exit 1
fi

targets="$(mktemp)"
trap 'rm -f "$targets"' EXIT

changed_files=0

for conf in "${confs[@]}"; do
  vmid="$(basename "$conf" .conf)"

  # 没有 link_down 直接跳过
  if ! grep -qE '^net[0-9]+:.*link_down=' "$conf"; then
    continue
  fi

  tmp="$(mktemp)"

  awk -v vmid="$vmid" -v out="$targets" '
    function normalize(v,   s) {
      s = v
      gsub(/(^|,)link_down=[01]/, "", s)   # 删光所有 link_down
      gsub(/^,+/, "", s)
      gsub(/,+$/, "", s)
      gsub(/,+/, ",", s)
      if (s == "") return "link_down=0"
      return s ",link_down=0"
    }
    {
      # 只处理 netX 行
      if ($0 ~ /^net[0-9]+: /) {
        split($0, a, ": ")
        k = a[1]
        v = a[2]

        # 统计 link_down= 出现次数（在 v 的副本上数）
        t = v
        cnt = gsub(/link_down=/, "", t)

        # 命中：重复 key 或者存在 link_down=1
        if (cnt > 1 || v ~ /(^|,)link_down=1(,|$)/) {
          nv = normalize(v)
          print k ": " nv
          print vmid "\t" k "\t" nv >> out
          next
        }
      }
      print $0
    }
  ' "$conf" > "$tmp"

  if ! cmp -s "$conf" "$tmp"; then
    bak="${conf}.bak.${ts}"
    cp -a "$conf" "$bak"
    mv "$tmp" "$conf"
    echo "✔ 修复 $conf  (备份: $(basename "$bak"))"
    changed_files=$((changed_files+1))
  else
    rm -f "$tmp"
  fi
done

echo
echo ">>> 文件级修复完成：改动文件数 = $changed_files"
echo ">>> 执行 qm set 正规化（只对命中项）..."
echo

if [[ ! -s "$targets" ]]; then
  echo ">>> 没有需要 qm set 的条目（可能都已干净）。"
  exit 0
fi

sort -u "$targets" | while IFS=$'\t' read -r vmid key new_value; do
  if qm set "$vmid" --"$key" "$new_value" >/dev/null 2>&1; then
    echo "  ✔ qm set VM $vmid $key OK"
  else
    echo "  !! qm set VM $vmid $key FAILED（请检查 $CONF_DIR/$vmid.conf 的 $key 行）"
  fi
done

echo
echo ">>> 最终验证：仍存在重复 link_down 的行会被列出（按文件扫描）"
grep -RInE '^net[0-9]+:.*link_down=([01].*)?link_down=' "$CONF_DIR" \
  || echo "OK: 未发现重复 link_down"

echo ">>> Done."
