package main

import (
	"bytes"
	"fmt"
	"os"
	"strconv"
	"strings"
	"text/template"
)

// 定义接口结构
type InterfaceConfig struct {
	Name    string
	MAC     string
	IP      string
	Prefix  string
	Mask    string
	Gateway string
}

// 定义模板内容
const netplanTemplate = `network:
  version: 2
  ethernets:
{{- range . }}
    {{ .Name }}:
      match:
        macaddress: {{ .MAC }}
      dhcp4: no
      addresses:
        - {{ .IP }}/{{ .Prefix }}
      gateway4: {{ .Gateway }}
      nameservers:
        addresses:
          - 8.8.8.8
          - 8.8.4.4
{{- end }}
`

// GenerateNetCardConfig 生成网卡配置
func GenerateNetCardConfig(netCardConfig []InterfaceConfig) (string, error) {
	// 创建模板
	for k, config := range netCardConfig {
		Prefix, err := maskToCIDR(config.Mask)
		if err != nil {
			return "", err
		}
		netCardConfig[k].Prefix = strconv.Itoa(Prefix)
	}

	tmpl, err := template.New("netplan").Parse(netplanTemplate)
	if err != nil {
		fmt.Println("Error parsing template:", err)
		return "", err
	}

	// 使用 bytes.Buffer 来捕获模板的输出
	var output bytes.Buffer

	// 执行模板并将结果写入到 output
	err = tmpl.Execute(&output, netCardConfig)
	if err != nil {
		fmt.Println("Error executing template:", err)
		return "", err
	}

	// 将生成的字符串打印出来
	return output.String(), nil
}

// 将子网掩码转换为CIDR前缀
func maskToCIDR(mask string) (int, error) {
	parts := strings.Split(mask, ".")
	cidr := 0
	for _, part := range parts {
		num, err := strconv.Atoi(part)
		if err != nil {
			return 0, err
		}
		bits := fmt.Sprintf("%08b", num)
		cidr += strings.Count(bits, "1")
	}
	return cidr, nil
}

func main() {
	// 定义接口配置
	netCardConfig := []InterfaceConfig{
		{
			Name:    "ens33",
			MAC:     "00:0c:29:0e:4f:8e",
			IP:      "192.168.1.1",
			Mask:    "255.255.255.0",
			Gateway: "192.168.1.1",
		},
		{
			Name:    "ens37",
			MAC:     "00:0c:29:0e:4f:90",
			IP:      "192.168.2.1",
			Mask:    "255.255.255.0",
			Gateway: "192.168.2.1",
		},
	}
	// 生成网卡配置
	config, err := GenerateNetCardConfig(netCardConfig)
	if err != nil {
		fmt.Println("生成网络配置文件失败:", err)
		return
	}
	create, err := os.Create("network-config")
	if err != nil {
		fmt.Println("创建配置文件失败:", err)
		return
	}
	defer create.Close()
	_, _ = create.WriteString(config)
}
