78 lines
1.7 KiB
Go
78 lines
1.7 KiB
Go
package cmd
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
|
|
"github.com/spf13/cobra"
|
|
"github.com/warkanum/unitdore/config"
|
|
"github.com/warkanum/unitdore/systemd"
|
|
)
|
|
|
|
var (
|
|
updateOrder int
|
|
updateEnable bool
|
|
updateDisable bool
|
|
)
|
|
|
|
var updateCmd = &cobra.Command{
|
|
Use: "update <name>",
|
|
Short: "Update a unit's config and recreate its service file",
|
|
Args: cobra.ExactArgs(1),
|
|
RunE: runUpdate,
|
|
}
|
|
|
|
func init() {
|
|
updateCmd.Flags().IntVar(&updateOrder, "order", 0, "set startup order")
|
|
updateCmd.Flags().BoolVar(&updateEnable, "enable", false, "enable the unit")
|
|
updateCmd.Flags().BoolVar(&updateDisable, "disable", false, "disable the unit")
|
|
rootCmd.AddCommand(updateCmd)
|
|
}
|
|
|
|
func runUpdate(cmd *cobra.Command, args []string) error {
|
|
if updateEnable && updateDisable {
|
|
return errors.New("--enable and --disable are mutually exclusive")
|
|
}
|
|
|
|
cfg, err := config.Load(configPath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
name := args[0]
|
|
u := cfg.FindUnit(name)
|
|
if u == nil {
|
|
return fmt.Errorf("unit %q not found", name)
|
|
}
|
|
|
|
if cmd.Flags().Changed("order") {
|
|
u.Order = updateOrder
|
|
fmt.Printf(" order → %d\n", u.Order)
|
|
}
|
|
if updateEnable {
|
|
u.Enabled = true
|
|
u.DisabledReason = ""
|
|
fmt.Printf(" enabled\n")
|
|
}
|
|
if updateDisable {
|
|
u.Enabled = false
|
|
fmt.Printf(" disabled\n")
|
|
}
|
|
|
|
if err := cfg.Save(configPath); err != nil {
|
|
return err
|
|
}
|
|
|
|
prefix, suffix, serviceUser := cfg.Prefix, cfg.Suffix, cfg.EffectiveServiceUser()
|
|
|
|
if systemd.IsInstalled(*u, prefix, suffix) {
|
|
if err := systemd.Install(*u, prefix, suffix, serviceUser); err != nil {
|
|
return fmt.Errorf("recreating service file: %w", err)
|
|
}
|
|
path, _ := systemd.UnitPath(*u, prefix, suffix)
|
|
fmt.Printf(" ✓ service file recreated: %s\n", path)
|
|
}
|
|
|
|
return nil
|
|
}
|