package nginx

import (
	"os"
	"text/template"

	"github.com/amalgam8/amalgam8/sidecar/config"
)

type sslTemplate struct {
	CertPath    string
	CertKeyPath string
	CACertPath  string
}

const (
	servicesConfTemplatePath = "/etc/nginx/amalgam8-services.conf.tmpl"
	servicesConfPath         = "/etc/nginx/amalgam8-services.conf"
)

// GenerateConfig generates a NGINX service config with SSL.
func GenerateConfig(conf config.ProxyConfig) error {
	sslTmpl := &sslTemplate{
		CertPath:    conf.CertPath,
		CertKeyPath: conf.CertKeyPath,
		CACertPath:  conf.CACertPath,
	}

	return executeTemplate(
		servicesConfTemplatePath,
		servicesConfPath,
		sslTmpl,
	)
}

// executeTemplate uses the template file to generate the target file.
func executeTemplate(templateFile, targetFile string, data interface{}) error {
	goTemplate, err := template.ParseFiles(templateFile)
	if err != nil {
		return err
	}

	file, err := os.Create(targetFile)
	if err != nil {
		return err
	}

	if err = goTemplate.Execute(file, data); err != nil {
		return err
	}

	return file.Close()
}
