//go:generate go run -mod=vendor github.com/UnnoTed/fileb0x b0x.toml

// I'm prototyping this out to be useful for more than just watchdog
// hence there are a few unnecessary things for the sake of the trying it out
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"text/template"

	"git.rootprojects.org/root/watchdog.go/cmd/install/static"
)

type Config struct {
	Name                string `json:"name"`
	Desc                string `json:"desc"`
	URL                 string `json:"url"`
	Exec                string `json:"exec"`
	Args                string `json:"args"`
	User                string `json:"user"`
	Group               string `json:"group"`
	Production          bool   `json:"production"`
	PrivilegedPorts     bool   `json:"privileged_ports"`
	MultiuserProtection bool   `json:"multiuser_protection"`
}

func main() {

	b, err := static.ReadFile("dist/etc/systemd/system/watchdog.service.tmpl")
	if err != nil {
		log.Fatal(err)
		return
	}
	s := string(b)

	j, err := static.ReadFile("dist/etc/systemd/system/watchdog.service.json")
	if err != nil {
		log.Fatal(err)
		return
	}

	//conf := map[string]string{}
	conf := &Config{}
	err = json.Unmarshal(j, &conf)
	if nil != err {
		log.Fatal(err)
		return
	}
	if "" == conf.Group {
		conf.Group = conf.User
	}

	serviceFile := conf.Exec + ".service"

	rw := &bytes.Buffer{}
	// not sure what the template name does, but whatever
	tmpl, err := template.New("service").Parse(s)
	if err != nil {
		log.Fatal(err)
		return
	}

	err = tmpl.Execute(rw, conf)
	if nil != err {
		log.Fatal(err)
		return
	}

	if err := ioutil.WriteFile(serviceFile, rw.Bytes(), 0644); err != nil {
		log.Fatalf("ioutil.WriteFile error: %v", err)
	}
	fmt.Printf("Wrote %q\n", serviceFile)
}
