// Copyright (c) The Thanos Authors.
// Licensed under the Apache License 2.0.

package objstore

import (
	
	
	
	
)

// NewTLSConfig creates a new tls.Config from the given TLSConfig.
func ( *TLSConfig) (*tls.Config, error) {
	 := &tls.Config{InsecureSkipVerify: .InsecureSkipVerify}

	// If a CA cert is provided then let's read it in.
	if len(.CAFile) > 0 {
		,  := readCAFile(.CAFile)
		if  != nil {
			return nil, 
		}
		if !updateRootCA(, ) {
			return nil, fmt.Errorf("unable to use specified CA cert %s", .CAFile)
		}
	}

	if len(.ServerName) > 0 {
		.ServerName = .ServerName
	}
	// If a client cert & key is provided then configure TLS config accordingly.
	if len(.CertFile) > 0 && len(.KeyFile) == 0 {
		return nil, fmt.Errorf("client cert file %q specified without client key file", .CertFile)
	} else if len(.KeyFile) > 0 && len(.CertFile) == 0 {
		return nil, fmt.Errorf("client key file %q specified without client cert file", .KeyFile)
	} else if len(.CertFile) > 0 && len(.KeyFile) > 0 {
		// Verify that client cert and key are valid.
		if ,  := .getClientCertificate(nil);  != nil {
			return nil, 
		}
		.GetClientCertificate = .getClientCertificate
	}

	return , nil
}

// readCAFile reads the CA cert file from disk.
func readCAFile( string) ([]byte, error) {
	,  := os.ReadFile()
	if  != nil {
		return nil, fmt.Errorf("unable to load specified CA cert %s: %s", , )
	}
	return , nil
}

// updateRootCA parses the given byte slice as a series of PEM encoded certificates and updates tls.Config.RootCAs.
func updateRootCA( *tls.Config,  []byte) bool {
	 := x509.NewCertPool()
	if !.AppendCertsFromPEM() {
		return false
	}
	.RootCAs = 
	return true
}

// getClientCertificate reads the pair of client cert and key from disk and returns a tls.Certificate.
func ( *TLSConfig) (*tls.CertificateRequestInfo) (*tls.Certificate, error) {
	,  := tls.LoadX509KeyPair(.CertFile, .KeyFile)
	if  != nil {
		return nil, fmt.Errorf("unable to use specified client cert (%s) & key (%s): %s", .CertFile, .KeyFile, )
	}
	return &, nil
}

// TLSConfig configures the options for TLS connections.
type TLSConfig struct {
	// The CA cert to use for the targets.
	CAFile string `yaml:"ca_file"`
	// The client cert file for the targets.
	CertFile string `yaml:"cert_file"`
	// The client key file for the targets.
	KeyFile string `yaml:"key_file"`
	// Used to verify the hostname for the targets.
	ServerName string `yaml:"server_name"`
	// Disable target certificate validation.
	InsecureSkipVerify bool `yaml:"insecure_skip_verify"`
}