package config

import (
	"os"
	"path/filepath"

	"gopkg.in/yaml.v3"
)

const (
	BaseDir = "/etc/sunhpc"
	LogDir  = "/var/log/sunhpc"
	TmplDir = BaseDir + "/tmpl.d"
)

var (
	SunHPCFile   = filepath.Join(BaseDir, "sunhpc.yaml")
	NodesFile    = filepath.Join(BaseDir, "nodes.yaml")
	NetworkFile  = filepath.Join(BaseDir, "network.yaml")
	DisksFile    = filepath.Join(BaseDir, "disks.yaml")
	ServicesFile = filepath.Join(BaseDir, "services.yaml")
	FirewallFile = filepath.Join(BaseDir, "iptables.yaml")
)

// InitDirs 创建所有必需目录
func InitDirs() error {
	dirs := []string{
		BaseDir,
		TmplDir,
		LogDir,
	}
	for _, d := range dirs {
		if err := os.MkdirAll(d, 0755); err != nil {
			return err
		}
	}
	return nil
}

// CreateDefaultConfigs 生成默认 YAML 配置文件
func CreateDefaultConfigs() error {
	files := map[string]interface{}{
		SunHPCFile:   DefaultSunHPC(),
		NodesFile:    DefaultNodes(),
		NetworkFile:  DefaultNetwork(),
		DisksFile:    DefaultDisks(),
		ServicesFile: DefaultServices(),
		FirewallFile: DefaultFirewall(),
	}

	for path, data := range files {
		if err := writeYAML(path, data); err != nil {
			return err
		}
	}
	return nil
}

func writeYAML(path string, data interface{}) error {
	f, err := os.Create(path)
	if err != nil {
		return err
	}
	defer f.Close()

	enc := yaml.NewEncoder(f)
	defer enc.Close()
	return enc.Encode(data)
}
