//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 installer

import (
	"os"
	"path/filepath"
	"strings"
)

type Config struct {
	Title               string            `json:"title"`
	Name                string            `json:"name"`
	Desc                string            `json:"desc"`
	URL                 string            `json:"url"`
	Interpreter         string            `json:"interpreter"` // i.e. node, python
	Exec                string            `json:"exec"`
	Argv                []string          `json:"argv"`
	Args                string            `json:"-"`
	Envs                map[string]string `json:"envs"`
	User                string            `json:"user"`
	Group               string            `json:"group"`
	home                string            `json:"-"`
	Local               string            `json:"local"`
	LogDir              string            `json:"-"`
	System              bool              `json:"system"`
	Restart             bool              `json:"restart"`
	Production          bool              `json:"production"`
	PrivilegedPorts     bool              `json:"privileged_ports"`
	MultiuserProtection bool              `json:"multiuser_protection"`
}

func Install(c *Config) error {
	if "" == c.Exec {
		c.Exec = c.Name
	}
	c.Args = strings.Join(c.Argv, " ")

	// TODO handle non-system installs
	// * ~/.local/opt/watchdog/watchdog
	// * ~/.local/share/watchdog/var/log/
	// * ~/.config/watchdog/watchdog.json
	if !c.System {
		home, err := os.UserHomeDir()
		if nil != err {
			return err
		}
		c.home = home
		c.Local = filepath.Join(c.home, ".local")
		c.LogDir = filepath.Join(c.home, ".local", "share", c.Name, "var", "log")
	} else {
		c.LogDir = "/var/log/" + c.Name
	}

	err := install(c)
	if nil != err {
		return err
	}

	return nil
}
