package main import ( "context" "encoding/json" "fmt" "os" "os/exec" "sort" "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/resolver" "github.com/spf13/cobra" ) func doctorCmd() *cobra.Command { var online bool cmd := &cobra.Command{Use: "doctor", Short: "Check configuration, programs, cache and optional NetBox connectivity", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { cfg, err := config.Load() if err != nil { return err } failed := false report := func(label string, err error) { if err != nil { failed = true fmt.Fprintf(cmd.OutOrStdout(), "FAIL %s: %v\n", label, err) } else { fmt.Fprintf(cmd.OutOrStdout(), "OK %s\n", label) } } report("configuration", nil) _, err = resolver.New(cfg.Resolver) report("resolver", err) programs := map[string]bool{"ssh": true, "sftp": true, "scp": true} for name, c := range cfg.Commands { programs[c.Args[0]] = true if len(c.Args) > 1 && !strings.HasPrefix(c.Args[1], "-") { switch c.Args[0] { case "bash", "sh", "python", "python3": f, err := os.Open(c.Args[1]) if err == nil { f.Close() } report("script "+name, err) } } } var names []string for p := range programs { names = append(names, p) } sort.Strings(names) for _, p := range names { _, err := exec.LookPath(p) report("program "+p, err) } report("cache", newCache(cfg).Load()) for _, instance := range instanceConfigs(cfg) { if config.IsKeyringToken(instance.Token) { _, err := resolveToken(*instance) report("keyring token "+instance.KeyringAccount(), err) } } if online { sources := cfg.NetBoxes if len(sources) == 0 && cfg.NetBox.URL != "" { sources = []config.NetBoxConfig{cfg.NetBox} } for _, s := range sources { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) token, version := clientToken(s) _, err := netbox.NewClient(s.URL, token, version).Search(ctx, "", netbox.SearchOptions{}) cancel() report("NetBox "+s.Name, err) } } if failed { return fmt.Errorf("doctor found problems") } return nil }} cmd.Flags().BoolVar(&online, "online", false, "Also query every NetBox instance") return cmd } func explainCmd() *cobra.Command { return &cobra.Command{Use: "explain HOST", Short: "Explain actual host resolution and effective SSH settings without connecting", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { cfg, err := config.Load() if err != nil { return err } h, err := resolveTargetE(cfg, args[0], false) if err != nil { return err } selectors := commandHost(h) user, port := hostDefaults(cfg, h) opts := hostOptions(cfg, h) var rules []int for i, r := range cfg.SSH.Rules { if r.Match.Matches(selectors) { rules = append(rules, i+1) } } strategy := h.Resolver if strategy == "" { if h.Origin == "static" { strategy = "static address" } else { strategy = "not recorded in this cache entry" } } return json.NewEncoder(cmd.OutOrStdout()).Encode(map[string]any{ "target": h.Name, "instance": selectors.Instance, "address": h.IP, "source": h.Origin, "cached_at": h.CachedAt, "status": h.Status, "site": h.Site.Name, "role": h.Role.Name, "platform": h.Platform.Name, "tenant": h.Tenant.Name, "netbox_id": h.ID, "location": h.LocationPath(), "resolver_order": cfg.Resolver.Strategies, "resolver_used": strategy, "matching_rules": rules, "user": user, "port": port, "ssh": opts, }) }} } func favoritesCmd() *cobra.Command { cmd := &cobra.Command{Use: "favorites", Short: "List or change favorite and pinned hosts", RunE: func(cmd *cobra.Command, _ []string) error { s, err := activity.Read() if err != nil { return err } var names []string for n := range s.Favorites { if s.Favorites[n] { names = append(names, n) } } sort.Strings(names) for _, n := range names { marker := "favorite" if s.Pinned[n] { marker = "pinned" } fmt.Fprintf(cmd.OutOrStdout(), "%s\t%s\n", n, marker) } return nil }} for _, action := range []string{"add", "remove", "pin", "unpin"} { cmd.AddCommand(&cobra.Command{Use: action + " HOST", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { target := args[0] if action == "add" || action == "pin" { cfg, err := config.Load() if err != nil { return err } h, err := resolveTargetE(cfg, target, false) if err != nil { return err } target = h.Name } return activity.Update(func(s *activity.State) { switch action { case "add": s.Favorites[target] = true case "pin": s.Favorites[target] = true s.Pinned[target] = true case "unpin": delete(s.Pinned, target) case "remove": delete(s.Favorites, target) delete(s.Pinned, target) } }) }}) } return cmd } func historyCmd() *cobra.Command { cmd := &cobra.Command{Use: "history", Short: "Show optional local action history", RunE: func(cmd *cobra.Command, _ []string) error { cfg, err := config.Load() if err != nil { return err } if err := activity.Update(func(s *activity.State) { activity.Prune(s, cfg.Activity) }); err != nil { return err } s, err := activity.Read() if err != nil { return err } for i := len(s.Records) - 1; i >= 0; i-- { r := s.Records[i] fmt.Fprintf(cmd.OutOrStdout(), "%s\t%s\t%s\texit=%d\t%s\n", r.Time.Format(time.RFC3339), r.Host, r.Command, r.Code, r.Duration.Round(time.Millisecond)) } return nil }} cmd.AddCommand(&cobra.Command{Use: "clear", Short: "Delete recorded actions, preserving favorites", Args: cobra.NoArgs, RunE: func(_ *cobra.Command, _ []string) error { return activity.Update(func(s *activity.State) { s.Records = nil }) }}) return cmd }