package clientutil

import (
	"crypto/tls"

	common "git.autistici.org/ai3/go-common"
)

// TLSClientConfig defines the TLS parameters for a client connection
// that should use a client X509 certificate for authentication.
type TLSClientConfig struct {
	Cert string `yaml:"cert"`
	Key  string `yaml:"key"`
	CA   string `yaml:"ca"`
}

// TLSConfig returns a tls.Config object with the current configuration.
func (c *TLSClientConfig) TLSConfig() (*tls.Config, error) {
	cert, err := tls.LoadX509KeyPair(c.Cert, c.Key)
	if err != nil {
		return nil, err
	}
	tlsConf := &tls.Config{
		Certificates: []tls.Certificate{cert},
	}

	if c.CA != "" {
		cas, err := common.LoadCA(c.CA)
		if err != nil {
			return nil, err
		}
		tlsConf.RootCAs = cas
	}
	tlsConf.BuildNameToCertificate()

	return tlsConf, nil
}