package main import ( "bufio" "context" "fmt" "io" "os" "strconv" "strings" "time" "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/activity" "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config" "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox" "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/runner" "github.com/charmbracelet/x/term" ) func commandHost(h resolvedHost) config.SSHHost { instance, name := netbox.SplitTarget(h.Name) return config.SSHHost{Instance: instance, Name: name, Kind: h.Kind, Tags: h.Tags, Status: h.Status, Site: h.Site, Role: h.Role, Platform: h.Platform, Tenant: h.Tenant} } func confirmAction(message string, yes bool) error { if yes { return nil } if !term.IsTerminal(os.Stdin.Fd()) { return fmt.Errorf("%s requires confirmation; use --yes for unattended execution", message) } fmt.Fprintf(os.Stderr, "%s? [y/N] ", message) answer, err := bufio.NewReader(os.Stdin).ReadString('\n') if err != nil { return err } if strings.EqualFold(strings.TrimSpace(answer), "y") || strings.EqualFold(strings.TrimSpace(answer), "yes") { return nil } return fmt.Errorf("cancelled") } func supervise(cfg *config.Config, h resolvedHost, name string, argv []string, post string, timeout time.Duration, status bool, stdin io.Reader, stdout, stderr io.Writer) int { start := time.Now() env := append(preConnectEnv(h, name), "NETSSH_COMMAND="+name) result := runner.Run(context.Background(), argv, runner.Options{Stdin: stdin, Stdout: stdout, Stderr: stderr, Env: env, Timeout: timeout, Status: status, Label: name + " " + h.Name}) code := result.Code if result.Started && config.HookCommand(post) != "" { hook := runner.Run(context.Background(), []string{"sh", "-c", post}, runner.Options{Stdin: nil, Stdout: stderr, Stderr: stderr, Env: append(env, "NETSSH_EXIT_CODE="+strconv.Itoa(code)), Timeout: 30 * time.Second}) if hook.Code != 0 { fmt.Fprintf(stderr, "post hook failed (exit %d)\n", hook.Code) if code == 0 { code = hook.Code } } } if err := activity.Append(cfg.Activity, activity.Record{Time: start, Host: h.Name, Command: name, Code: code, Duration: time.Since(start)}); err != nil { fmt.Fprintf(stderr, "activity: %v\n", err) } return code }