package builder import ( "context" "errors" "fmt" "io" "os" "strings" "git.gsdistance.org/tyuXX/RUD/internal/config" ) // Options configures a rud config builder session. type Options struct { ConfigPath string ForceNew bool Plain bool NoColor bool In io.Reader Out io.Writer } // Run launches the interactive configuration builder CLI. func Run(ctx context.Context, opts Options) error { path := strings.TrimSpace(opts.ConfigPath) if path == "" { path = "rud.json" } ui := NewUI(opts.In, opts.Out, opts.Plain, opts.NoColor) var cfg *config.Config var originalRaw []byte var baselineJSON string isNewFile := false _, statErr := os.Stat(path) fileExists := statErr == nil if !opts.ForceNew && fileExists { loaded, raw, loadErr := config.LoadForEdit(path) if loadErr != nil { ui.Error(fmt.Sprintf("Could not load %s: %v", path, loadErr)) recOpts := []Option{ {Label: "Start a new config from a template", Description: "Existing file will not be modified until you Save"}, {Label: "Exit"}, } idx, ok, err := ui.Select("Config Load Error", "", recOpts, 1) if err != nil { return err } if !ok || idx == 1 { return nil } isNewFile = true } else { cfg = loaded originalRaw = raw if b, err := config.MarshalConfig(cfg); err == nil { baselineJSON = string(b) } ui.Ok(fmt.Sprintf("Loaded existing configuration from %s", path)) } } else { isNewFile = true } if cfg == nil { starter, ok, err := newConfigStarterFlow(ctx, ui, path, fileExists) if err != nil { return err } if !ok { return nil } cfg = starter } return runSectionHub(ctx, ui, cfg, path, isNewFile, baselineJSON, originalRaw) } func newConfigStarterFlow(ctx context.Context, ui *UI, path string, fileExists bool) (*config.Config, bool, error) { sub := fmt.Sprintf("Target file: %s", path) if fileExists { sub += " (will be overwritten only when you Save)" } opts := []Option{ {Label: "Guided Quick-Start Wizard", Description: "Step-by-step setup for server, monitors, alerts, and theme"}, {Label: "Default Demo Config", Description: "All 5 check methods + sample event + dark minimal page"}, {Label: "Web & API Starter", Description: "HTTPS endpoints, DNS check, outage alert, grouped layout"}, {Label: "Homelab / Infrastructure Starter", Description: "Gateway ping, DB TCP, reverse proxy HTTP, disk space cmd"}, {Label: "Blank Minimal Config", Description: "Empty monitors & events with a clean status page scaffold"}, {Label: "Exit"}, } idx, ok, err := ui.Select("Create New RUD Configuration", sub, opts, 0) if err != nil { return nil, false, err } if !ok || idx == len(opts)-1 { return nil, false, nil } switch idx { case 0: cfg := BlankMinimalConfig() if err := runQuickStartWizard(ctx, ui, &cfg); err != nil { return nil, false, err } return &cfg, true, nil case 1: cfg := config.DefaultConfig() return &cfg, true, nil case 2: cfg := WebAPIStarterConfig() return &cfg, true, nil case 3: cfg := HomelabStarterConfig() return &cfg, true, nil case 4: cfg := BlankMinimalConfig() return &cfg, true, nil default: return nil, false, nil } } func runQuickStartWizard(ctx context.Context, ui *UI, cfg *config.Config) error { ui.Header("Quick-Start Wizard (1/4): Server", "Configure the single HTTP endpoint served by RUD") listen, err := ui.PromptString("Listen address", cfg.Server.Listen, "host:port or :8080", false, requireNonEmpty("listen")) if err != nil { return err } cfg.Server.Listen = listen endpoint, err := ui.PromptString("HTTP endpoint path", cfg.Server.Endpoint, "must start with /", false, requireNonEmpty("endpoint")) if err != nil { return err } if !strings.HasPrefix(endpoint, "/") { endpoint = "/" + endpoint } cfg.Server.Endpoint = endpoint ui.Header("Quick-Start Wizard (2/4): Monitors", "Add one or more services to monitor") for { added, err := addMonitorFlow(ctx, ui, cfg) if err != nil { return err } if !added && len(cfg.Monitors) == 0 { break } more, err := ui.Confirm("Add another monitor?", false) if err != nil { return err } if !more { break } } ui.Header("Quick-Start Wizard (3/4): Alerts & Events", "Optional outbound webhooks or commands on outage/recovery") addEv, err := ui.Confirm("Configure an alert event rule now?", false) if err != nil { return err } if addEv { if err := addEventFlow(ui, cfg); err != nil { return err } } ui.Header("Quick-Start Wizard (4/4): Status Page & Theme", "Customize your public status page") title, err := ui.PromptString("Page title", cfg.Page.Title, "shown in browser tab & header", false, requireNonEmpty("title")) if err != nil { return err } cfg.Page.Title = title for i := range cfg.Page.Elements { if cfg.Page.Elements[i].Type == "header" { cfg.Page.Elements[i].Title = title } } pickTheme, err := ui.Confirm("Choose a color theme preset?", true) if err != nil { return err } if pickTheme { if err := applyThemePresetFlow(ui, &cfg.Page); err != nil { return err } } ui.Ok("Quick-start setup complete! Opening the configuration hub for further edits or saving.") return nil } func runSectionHub(ctx context.Context, ui *UI, cfg *config.Config, path string, isNewFile bool, baselineJSON string, originalRaw []byte) error { for { currBytes, err := config.MarshalConfig(cfg) if err != nil { return err } currJSON := string(currBytes) dirty := isNewFile || currJSON != baselineJSON lintRaw := currBytes if !dirty && len(originalRaw) > 0 { lintRaw = originalRaw } valErr, lintIssues := evaluateConfigHealth(cfg, lintRaw) statusBadge := ui.Green("[saved]") if isNewFile { statusBadge = ui.Yellow("[new unsaved]") } else if dirty { statusBadge = ui.Yellow("[modified]") } var healthLine string if valErr != nil { healthLine = ui.Red("✗ Invalid: " + valErr.Error()) } else if len(lintIssues) > 0 { healthLine = ui.Yellow(fmt.Sprintf("! Valid with %d warning(s)", len(lintIssues))) } else { healthLine = ui.Green("✓ Valid (0 warnings)") } sub := fmt.Sprintf("File: %s %s\nSummary: %d monitor(s) | %d event(s) | %d page element(s)\nHealth: %s", path, statusBadge, len(cfg.Monitors), len(cfg.Events), len(cfg.Page.Elements), healthLine) opts := []Option{ {Label: fmt.Sprintf("Monitors (%d)", len(cfg.Monitors)), Description: "Add, edit, reorder, duplicate, delete, or test checks live"}, {Label: fmt.Sprintf("Events & Alerts (%d)", len(cfg.Events)), Description: "Alert recipes, nested AND/OR condition tree, webhooks & commands"}, {Label: fmt.Sprintf("Page & Theme (%d elements)", len(cfg.Page.Elements)), Description: "Theme presets, colors, layout elements & display flags"}, {Label: "Server Settings", Description: fmt.Sprintf("listen=%s endpoint=%s refresh=%s", cfg.Server.Listen, cfg.Server.Endpoint, cfg.Server.RefreshInterval.Std())}, {Label: "Defaults & Storage", Description: fmt.Sprintf("interval=%s timeout=%s history=%d", cfg.Defaults.Interval.Std(), cfg.Defaults.Timeout.Std(), cfg.Storage.HistorySize)}, {Label: "Test Monitors Live", Description: "Run health checks immediately against live targets"}, {Label: "Validate & Preview JSON / Diff", Description: "Check errors/warnings, view changes, or inspect full JSON"}, {Label: "Save", Description: fmt.Sprintf("Write atomically to %s", path)}, {Label: "Save As...", Description: "Save configuration to a different file path"}, {Label: "Exit"}, } idx, ok, err := ui.Select("RUD Config Builder", sub, opts, 0) if err != nil { if errors.Is(err, ErrAborted) { return err } return err } if !ok || idx == 9 { if !dirty { return nil } exitOpts := []Option{ {Label: "Save & Exit", Description: "Validate and write changes to " + path}, {Label: "Discard changes & Exit"}, {Label: "Cancel (return to hub)"}, } eIdx, eOK, eErr := ui.Select("Unsaved Changes", fmt.Sprintf("%s has unsaved changes.", path), exitOpts, 0) if eErr != nil { return eErr } if !eOK || eIdx == 2 { continue } if eIdx == 0 { saved, sErr := saveConfigFlow(ui, cfg, &path, &isNewFile, &baselineJSON, &originalRaw, false) if sErr != nil { return sErr } if saved { return nil } continue } return nil } switch idx { case 0: if err := editMonitors(ctx, ui, cfg); err != nil { return err } case 1: if err := editEvents(ui, cfg); err != nil { return err } case 2: if err := editPage(ui, cfg); err != nil { return err } case 3: if err := editServer(ui, cfg); err != nil { return err } case 4: if err := editDefaultsAndStorage(ui, cfg); err != nil { return err } case 5: if len(cfg.Monitors) == 0 { ui.Warn("No monitors configured yet.") } else if err := testMonitorsMenu(ctx, ui, cfg); err != nil { return err } case 6: if err := previewAndValidateMenu(ui, cfg, baselineJSON, currJSON, lintRaw); err != nil { return err } case 7: if _, err := saveConfigFlow(ui, cfg, &path, &isNewFile, &baselineJSON, &originalRaw, false); err != nil { return err } case 8: if _, err := saveConfigFlow(ui, cfg, &path, &isNewFile, &baselineJSON, &originalRaw, true); err != nil { return err } } } } func evaluateConfigHealth(cfg *config.Config, rawJSON []byte) (error, []config.LintIssue) { cloned, err := cfg.Clone() if err != nil { return err, nil } cloned.ApplyFallbacks() valErr := cloned.Validate() issues := cloned.Lint(rawJSON) return valErr, issues } func previewAndValidateMenu(ui *UI, cfg *config.Config, baselineJSON, currJSON string, rawJSON []byte) error { valErr, issues := evaluateConfigHealth(cfg, rawJSON) ui.Header("Validation & Lint Report", "") if valErr != nil { ui.Error("Validation failed: " + valErr.Error()) } else { ui.Ok("Configuration schema is valid.") } if len(issues) == 0 { ui.Ok("No lint warnings.") } else { ui.Warn(fmt.Sprintf("%d lint warning(s):", len(issues))) for _, iss := range issues { ui.Println(" - " + iss.String()) } } opts := []Option{ {Label: "Show changes diff"}, {Label: "Show full JSON preview"}, {Label: "Back"}, } for { idx, ok, err := ui.Select("Preview", "", opts, 2) if err != nil { return err } if !ok || idx == 2 { return nil } switch idx { case 0: ui.Header("Changes Diff", "") if baselineJSON == "" { ui.Println(FormatDiff("", currJSON)) } else { ui.Println(FormatDiff(baselineJSON, currJSON)) } case 1: ui.Header("Generated JSON Preview", "") ui.Println(currJSON) } } } func saveConfigFlow(ui *UI, cfg *config.Config, activePath *string, isNewFile *bool, baselineJSON *string, originalRaw *[]byte, saveAs bool) (bool, error) { targetPath := *activePath if saveAs { p, err := ui.PromptString("Save As path", targetPath, "file path", false, requireNonEmpty("path")) if err != nil { return false, err } targetPath = p } currBytes, err := config.MarshalConfig(cfg) if err != nil { return false, err } valErr, issues := evaluateConfigHealth(cfg, currBytes) if valErr != nil { ui.Error("Validation error: " + valErr.Error()) force, cErr := ui.Confirm("Configuration has validation errors. Save anyway?", false) if cErr != nil { return false, cErr } if !force { return false, nil } } if len(issues) > 0 { ui.Warn(fmt.Sprintf("%d lint warning(s):", len(issues))) for _, iss := range issues { ui.Println(" - " + iss.String()) } cont, cErr := ui.Confirm("Proceed with saving?", true) if cErr != nil { return false, cErr } if !cont { return false, nil } } makeBackup := false if _, statErr := os.Stat(targetPath); statErr == nil { ans, cErr := ui.Confirm(fmt.Sprintf("Create backup (%s.bak) before overwriting?", targetPath), true) if cErr != nil { return false, cErr } makeBackup = ans } bakPath, err := config.SaveConfigWithBackup(targetPath, cfg, makeBackup) if err != nil { ui.Error(fmt.Sprintf("Save failed: %v", err)) return false, nil } *activePath = targetPath *isNewFile = false *baselineJSON = string(currBytes) *originalRaw = currBytes ui.Ok("Saved configuration to " + targetPath) if bakPath != "" { ui.Info("Created backup at " + bakPath) } return true, nil }