#!/bin/bash
source /etc/profile
# 1. 获取并验证带外IP
OOB_IP=$(ipmitool lan print 1 | grep "IP Address" | grep -v "Source" | awk '{print $4}')
if [ -z "$OOB_IP" ]; then
    echo "[错误] 无法获取带外IP地址，请检查ipmitool是否正常"
    exit 1
fi

# 2. 匹配ip.txt中的配置
IP_INFO=$(grep "$OOB_IP" /opt/ip.txt)
if [ -z "$IP_INFO" ]; then
    echo "[错误] 在/opt/ip.txt中未找到带外IP $OOB_IP 对应的配置"
    exit 1
fi

# 3. 解析配置参数
INBAND_IP=$(echo "$IP_INFO" | awk '{print $1}')
NETMASK=$(echo "$IP_INFO" | awk '{print $2}')
GATEWAY=$(echo "$IP_INFO" | awk '{print $3}')

# 4. 显示匹配到的配置（清晰排版）
echo "======================================"
echo "已匹配到网络配置："
echo "带外IP        : $OOB_IP"
echo "带内IP/掩码   : $INBAND_IP/$NETMASK"
echo "网关          : $GATEWAY"
echo "======================================"

# 5. 配置文件路径与备份
NETPLAN_FILE="/etc/netplan/00-installer-config.yaml"
BACKUP_FILE="${NETPLAN_FILE}.bak-$(date +%Y%m%d%H%M%S)"
cp "$NETPLAN_FILE" "$BACKUP_FILE"
echo "[提示] 已创建配置备份：$BACKUP_FILE"

# 6. 执行替换（逻辑不变，保留精确匹配）
# 替换带内IP/掩码
sed -i "/bonds:/,/interfaces:/ s/- [0-9.]\+\/[0-9]\+/- $INBAND_IP\/$NETMASK/" "$NETPLAN_FILE"
# 替换网关
sed -i '/- to: default/ {n; s/via: [0-9.]\+/via: '"$GATEWAY"'/}' "$NETPLAN_FILE"


# 7.持久化网络接口命名
echo -e "移动udev规则文件并应用"
cp -a /opt/70-persistent-* /etc/udev/rules.d/
systemctl restart openibd.service && netplan apply

# 8 修改主名称
echo -e "修改主机名称"
hostnamectl set-hostname "${INBAND_IP//./-}"
bash

# 9.清理记录
echo -e "清除记录"
crontab -l | grep -v '@reboot bash /opt/set_ip.sh > /tmp/ip_tmp.log' | crontab -
>/opt/ip.txt

# 10. 最终提示
echo -e "[完成] 网络配置已更新，可通过 'ip addr show eth0' 查看实际生效情况"
exit 0