Files
unitdore/systemd/generator.go
sgcommand 203e8e3f04 Phase 3+4: systemd generator, install, active, status
- systemd/generator.go: build .service file content from Unit
- systemd/manager.go: install/uninstall/enable/disable/status via systemctl
- cmd/install.go: write unit files, --dry-run flag, remove disabled units
- cmd/active.go: enable + start units in order
- cmd/status.go: summary table with name/runtime/user/enabled/installed/state
2026-04-03 14:46:25 +02:00

106 lines
2.3 KiB
Go

package systemd
import (
"fmt"
"strings"
"text/template"
"github.com/warkanum/unitdore/config"
)
const systemUnitTemplate = `# /etc/systemd/system/{{.ServiceName}}
# Generated by unitdore — do not edit manually
[Unit]
Description=Unitdore: {{.Unit.Name}} ({{.Unit.Runtime}})
After=network.target
[Service]
Type=simple
ExecStart={{.ExecStart}}
ExecStop={{.ExecStop}}
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
`
const userUnitTemplate = `# ~/.config/systemd/user/{{.ServiceName}}
# Generated by unitdore — do not edit manually
[Unit]
Description=Unitdore: {{.Unit.Name}} ({{.Unit.Runtime}})
After=default.target
[Service]
Type=simple
ExecStart={{.ExecStart}}
ExecStop={{.ExecStop}}
Restart=on-failure
RestartSec=5
[Install]
WantedBy=default.target
`
type templateData struct {
ServiceName string
Unit config.Unit
ExecStart string
ExecStop string
}
// ServiceName returns the systemd service name for a unit.
func ServiceName(u config.Unit) string {
return fmt.Sprintf("unitdore-%s.service", u.Name)
}
// Generate produces the .service file content for a unit.
func Generate(u config.Unit) (string, error) {
execStart, execStop := buildExecCommands(u)
data := templateData{
ServiceName: ServiceName(u),
Unit: u,
ExecStart: execStart,
ExecStop: execStop,
}
tmplStr := systemUnitTemplate
if u.User != "" {
tmplStr = userUnitTemplate
}
tmpl, err := template.New("unit").Parse(tmplStr)
if err != nil {
return "", fmt.Errorf("parsing template: %w", err)
}
var buf strings.Builder
if err := tmpl.Execute(&buf, data); err != nil {
return "", fmt.Errorf("rendering template: %w", err)
}
return buf.String(), nil
}
func buildExecCommands(u config.Unit) (start, stop string) {
// If a custom command is provided, use it directly
if u.Command != "" {
return u.Command, ""
}
switch u.Runtime {
case "podman":
start = fmt.Sprintf("/usr/bin/podman start -a %s", u.Name)
stop = fmt.Sprintf("/usr/bin/podman stop %s", u.Name)
case "docker":
start = fmt.Sprintf("/usr/bin/docker start %s", u.Name)
stop = fmt.Sprintf("/usr/bin/docker stop %s", u.Name)
default:
start = fmt.Sprintf("/usr/bin/%s start %s", u.Runtime, u.Name)
stop = fmt.Sprintf("/usr/bin/%s stop %s", u.Runtime, u.Name)
}
return start, stop
}