package config

import (
	"flag"
	"fmt"
	"os"

	"gopkg.in/yaml.v3"
)

// Yaml struct of config
type YamlConfig struct {
	//证书配置
	CA struct {
		RootCert   string `yaml:"rootCert"`   //root CA证书存放路径
		Cert       string `yaml:"cert"`       // 服务端CA证书存放路径
		PrivateKey string `yaml:"privateKey"` // 服务端私钥存放路径
		Check      bool   `yaml:"check"`      // 是否开启服务端证书检查功能
	} `json:"ca"`
}

var CaConfig YamlConfig

func ReadConfig(configFile string) {
	yamlFile, err := os.ReadFile(configFile)
	if err != nil {
		fmt.Println("Read yaml config file error:", err)
		os.Exit(2)
	}

	err = yaml.Unmarshal(yamlFile, &CaConfig)
	if err != nil {
		fmt.Println("Unmarshal error:", err)
		os.Exit(3)
	}
}

var UserName *string

const defaultConfigFile = "./etc/cmca.yaml"

func init() {
	cfile := flag.String("c", defaultConfigFile, "config file")
	pv := flag.Bool("v", false, "print version")
	ph := flag.Bool("h", false, "print help")
	UserName = flag.String("u", "admin", "user name")

	flag.Parse()
	if *pv {
		os.Exit(0)
	}
	if *ph {
		flag.Usage()
		os.Exit(0)
	}

	ReadConfig(*cfile)
}
