Newer
Older
EnvoyControlPlane / internal / pkg / cert / factory.go
package cert

import (
	"fmt"
	"os"
	"strconv"

	"envoy-control-plane/internal/pkg/cert/api"
	"envoy-control-plane/internal/pkg/cert/letsencrypt"
)

// NewCertIssuer is a factory function that creates a CertIssuer based on the provided type name.
// It allows the rest of the application to obtain an issuer without knowing the specific
// underlying implementation details.
func NewCertIssuer(issuerType string) (api.CertIssuer, error) {
	switch issuerType {
	case "letsencrypt":
		// 1. Check the environment variable for staging mode.
		// We use Getenv, which returns an empty string if the variable is not set.
		stagingEnv := os.Getenv("LETSENCRYPT_STAGING")

		// 2. Default to production (false).
		useStaging := false

		// 3. Try to parse the environment variable value as a boolean.
		// Common values like "1", "t", "T", "true", "TRUE" are interpreted as true.
		if stagingEnv != "" {
			parsedBool, err := strconv.ParseBool(stagingEnv)
			if err == nil {
				useStaging = parsedBool
			} else {
				// Optional: Log a warning if the value is set but invalid (e.g., LETSENCRYPT_STAGING=maybe)
				fmt.Printf("Warning: Invalid value for LETSENCRYPT_STAGING ('%s'). Defaulting to production.\n", stagingEnv)
			}
		}

		// 4. Return the concrete *letsencrypt.LetsEncryptIssuer with the determined setting.
		return &letsencrypt.LetsEncryptIssuer{
			UseStaging: useStaging,
		}, nil

	// Add new certificate authority implementations here as new cases
	// case "zerossl":
	//     return &zerossl.ZeroSSLIssuer{}, nil

	default:
		return nil, fmt.Errorf("unknown certificate issuer type: %s. Valid types: letsencrypt", issuerType)
	}
}