templatefile/cmd/bootstraper/main.go

106 lines
2.7 KiB
Go

package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"forge.cadoles.com/pcaseiro/templatefile/pkg/configs"
"github.com/alexflint/go-arg"
)
func processGlobal(global configs.Service, templateDir string) error {
fmt.Printf("FIXME Global %v %s\n", global, templateDir)
return nil
}
func processConfigFiles(tpls []configs.ConfigFile, variables map[string]interface{}, templateDir string) error {
values, err := json.Marshal(variables)
if err != nil {
return fmt.Errorf("Error unmarshaling values on template process; %v", err)
}
for _, tpl := range tpls {
if err := tpl.Generate("/tmp/test", templateDir, values); err != nil {
return fmt.Errorf("Template %s generation failed with error %v", tpl.Source, err)
}
}
return nil
}
func processDaemons(daemon configs.SystemService) error {
return daemon.Manage()
}
func processService(conf configs.Service, templateDir string) error {
err := processConfigFiles(conf.ConfigFiles, conf.Vars, templateDir)
if err != nil {
return fmt.Errorf("ProcessingTemplatesFailed with error: %v", err)
}
err = processDaemons(conf.Daemon)
if err != nil {
return fmt.Errorf("Error managing service daemons: %v", err)
}
return nil
}
func processConfig(confpath string, templateDir string) (configs.TemplaterConfig, error) {
var cnf configs.TemplaterConfig
flContent, err := os.ReadFile(confpath)
if err != nil {
return cnf, fmt.Errorf("Confiuration read failed with error: %v", err)
}
err = json.Unmarshal(flContent, &cnf)
if err != nil {
return cnf, fmt.Errorf("Processing config failed with error: %v", err)
}
for name, svr := range cnf.Services {
if name == "Global" {
err = processGlobal(svr, templateDir)
if err != nil {
return cnf, fmt.Errorf("Error processing globals: %v", err)
}
} else {
if err = processService(svr, templateDir); err != nil {
return cnf, fmt.Errorf("Error processing service: %v", err)
}
}
}
return cnf, nil
}
func main() {
var args struct {
ConfigDirectory string `arg:"-c,--config-dir,env:CONFIG_DIR" help:"Configuration values directory path" default:"./data/config"`
ConfigFile string `arg:"-f,--config-file,env:CONFIG_FILE" help:"Configuration file to procedss"`
TemplateDirectory string `arg:"-t,--template-dir,env:TEMPLATE_DIR" help:"Template directory path" default:"./data/templates"`
}
arg.MustParse(&args)
if args.ConfigFile != "" {
_, err := processConfig(args.ConfigFile, args.TemplateDirectory)
if err != nil {
panic(err)
}
} else {
files, err := ioutil.ReadDir(args.ConfigDirectory)
if err != nil {
panic(err)
}
for _, file := range files {
fname := fmt.Sprintf("%s/%s", args.ConfigDirectory, file.Name())
processConfig(fname, args.TemplateDirectory)
}
}
}