#!/bin/bash

# 检查是否以 root 用户运行
if [ "$EUID" -ne 0 ]; then
  echo "请以 root 用户运行此脚本！"
  exit 1
fi

# 自动检测网卡名称
NIC=$(ip -6 addr | grep -B1 'scope global' | awk -F': ' '/^[0-9]+:/{print $2}' | head -n 1)

# 检查是否找到网卡
if [ -z "$NIC" ]; then
  echo "未找到具有 IPv6 地址的网络接口，请确保网络已配置并启用 IPv6。"
  exit 1
fi

# 自动检测公网 IPv6 地址及掩码（排除 fd00 和 fe80 地址）
PUBLIC_IP_WITH_MASK=$(ip -6 addr show dev $NIC | grep 'scope global' | grep -v fd00 | grep -v fe80 | awk '{print $2}')
PUBLIC_IP=$(echo "$PUBLIC_IP_WITH_MASK" | cut -d'/' -f1)
PUBLIC_MASK=$(echo "$PUBLIC_IP_WITH_MASK" | cut -d'/' -f2)

# 检查是否找到公网 IPv6 地址
if [ -z "$PUBLIC_IP" ]; then
  echo "未找到公网 IPv6 地址，确保 $NIC 接口已配置并启用 IPv6。"
  exit 1
fi

# 修改 preferred_lft 为 0
ip -6 addr change "$PUBLIC_IP_WITH_MASK" dev $NIC preferred_lft 0
if [ $? -ne 0 ]; then
  echo "修改 preferred_lft 失败，请检查网络配置。"
  exit 1
fi

# 自动检测本地 fd 开头的 IPv6 地址及掩码
FD_IP_WITH_MASK=$(ip -6 addr show dev $NIC | grep 'scope global' | grep fd00 | awk '{print $2}')
FD_IP=$(echo "$FD_IP_WITH_MASK" | cut -d'/' -f1)
FD_MASK=$(echo "$FD_IP_WITH_MASK" | cut -d'/' -f2)

# 确保 /etc/network/interfaces.d/50-cloud-init 存在
CONFIG_FILE="/etc/network/interfaces.d/50-cloud-init"
if [ ! -f "$CONFIG_FILE" ]; then
  echo "创建 $CONFIG_FILE 文件。"
  touch "$CONFIG_FILE"
fi

# 清理旧配置并写入新配置
cat <<EOF > "$CONFIG_FILE"
auto lo
iface lo inet loopback

auto $NIC
iface $NIC inet6 static
    address $PUBLIC_IP/$PUBLIC_MASK
    gateway $(ip -6 route show default | grep -oP '(?<=via )[^ ]+')
    post-up ip -6 addr change $PUBLIC_IP/$PUBLIC_MASK dev $NIC preferred_lft 0

iface $NIC inet6 static
    address $FD_IP/$FD_MASK
    dns-nameservers 2001:4860:4860::8888 2001:4860:4860::8844
EOF

# 检测系统并选择重启网络的命令
if command -v systemctl &> /dev/null; then
  echo "应用新配置并重启网络服务 (systemctl)..."
  systemctl restart networking
elif command -v service &> /dev/null; then
  echo "应用新配置并重启网络服务 (service)..."
  service networking restart
elif command -v netplan &> /dev/null; then
  echo "应用新配置并重新加载网络 (netplan)..."
  netplan apply
else
  echo "无法自动重启网络服务，请手动检查网络配置。"
  exit 1
fi

if [ $? -eq 0 ]; then
  echo "配置成功！深圳公网 IPv6 地址：$PUBLIC_IP/$PUBLIC_MASK 和内网 IPv6 地址：$FD_IP/$FD_MASK 已永久化。"
else
  echo "网络服务重启失败，请检查配置文件是否正确。"
fi
