package daecommon

import (
	"isle/toolkit"
	"os"
	"path/filepath"
	"sync"

	"github.com/adrg/xdg"
)

// EnvVars are variables which are derived based on the environment which the
// process is running in.
type EnvVars struct {
	StateDir   toolkit.Dir
	RuntimeDir toolkit.Dir
}

// GetEnvVars will return the EnvVars of the current processes, as determined by
// the process's environment.
var GetEnvVars = sync.OnceValue(func() EnvVars {
	// RUNTIME_DIRECTORY/STATE_DIRECTORY are used by the systemd service in
	// conjunction with the RuntimeDirectory/StateDirectory directives.

	var (
		res EnvVars

		stateDirPath = envOr(
			"STATE_DIRECTORY",
			func() string { return filepath.Join(xdg.StateHome, "isle") },
		)

		runtimeDirPath = envOr(
			"RUNTIME_DIRECTORY",
			func() string { return filepath.Join(xdg.RuntimeDir, "isle") },
		)
	)

	h := new(toolkit.MkDirHelper)
	res.StateDir, _ = h.Maybe(toolkit.MkDir(stateDirPath, true))
	res.RuntimeDir, _ = h.Maybe(toolkit.MkDir(runtimeDirPath, true))

	if err := h.Err(); err != nil {
		panic(err)
	}

	return res
})

////////////////////////////////////////////////////////////////////////////////
// Jigs

func envOr(name string, fallback func() string) string {
	if v := os.Getenv(name); v != "" {
		return v
	}
	return fallback()
}