@opscompass/opscompass-cli 1.3.2 → 1.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,826 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import readline from "node:readline/promises";
4
+ import { format } from "node:util";
5
+
6
+ import { canReadStoredCredentials } from "../../credentials.js";
7
+ import { cliCommand, opscompassHome } from "../../environment/current.js";
8
+ import { getOpsCompassClient } from "../../opscompass.js";
9
+ import { updateDefaults } from "../../modules/defaults.js";
10
+ import { materializeMonitoringConfiguration } from "../../modules/license-manager.js";
11
+ import { downloadScriptsToHome } from "../homeInteraction.js";
12
+ import {
13
+ DATA_GATHERING_EXIT_CODES,
14
+ DataGatheringError,
15
+ } from "./events.js";
16
+ import {
17
+ OLM_DATA_PARMS_PATH,
18
+ writeOlmDataParms,
19
+ } from "./olmDataParms.js";
20
+ import {
21
+ LEGACY_INSTALLER_PATH,
22
+ runValidateInstallCommand,
23
+ } from "./validateInstall.js";
24
+ import { createDataGatheringUi } from "./ui.js";
25
+
26
+ const DEFAULT_USE_FILEDROP = "OC";
27
+ const DEFAULT_AUTOUPDATE_CONFIGS = "true";
28
+ const DEFAULT_AUTOUPDATE_SCRIPTS = "false";
29
+ const SUPPORTED_USE_FILEDROP_VALUES = new Set(["OC", "FD", "OC|FD", "NO"]);
30
+ const DEFAULT_MONITORING_CONFIGURATION_NAME = "Default-CLI";
31
+ const DEFAULTS_PATH = path.join(opscompassHome, "defaults.json");
32
+ const LEGACY_LMBASE_PATH = path.join(opscompassHome, "scripts", "base-scripts", "src");
33
+
34
+ function writeSetupStderr(message, ...args) {
35
+ console.error(format(message, ...args));
36
+ }
37
+
38
+ function createSetupScriptOutput(logger) {
39
+ return {
40
+ log(message, ...args) {
41
+ writeSetupStderr(message, ...args);
42
+ },
43
+ warn(message, ...args) {
44
+ const formatted = format(message, ...args);
45
+ logger.emit("setup.script_warning", {
46
+ message: formatted,
47
+ });
48
+ console.error(formatted);
49
+ },
50
+ error(message, ...args) {
51
+ const formatted = format(message, ...args);
52
+ logger.emit("setup.script_error", {
53
+ message: formatted,
54
+ });
55
+ console.error(formatted);
56
+ },
57
+ };
58
+ }
59
+
60
+ function createSetupConfigOutput() {
61
+ return {
62
+ log() {},
63
+ warn(message, ...args) {
64
+ writeSetupStderr(message, ...args);
65
+ },
66
+ error(message, ...args) {
67
+ writeSetupStderr(message, ...args);
68
+ },
69
+ };
70
+ }
71
+
72
+ function readRequiredFlagValue(args, index, flagName) {
73
+ const value = args[index + 1];
74
+ if (value === undefined || value.startsWith("--")) {
75
+ throw new DataGatheringError(`${flagName} requires a value`, {
76
+ exitCode: DATA_GATHERING_EXIT_CODES.invalidInput,
77
+ type: "setup.invalid-input",
78
+ data: {
79
+ flag: flagName,
80
+ },
81
+ });
82
+ }
83
+
84
+ return value;
85
+ }
86
+
87
+ function parseSetupArgs(args) {
88
+ const options = {
89
+ nonInteractive: false,
90
+ company: undefined,
91
+ account: undefined,
92
+ monitoringConfigurationId: undefined,
93
+ dataDir: undefined,
94
+ logDir: undefined,
95
+ oracleHome: undefined,
96
+ useFileDrop: undefined,
97
+ fdUrl: undefined,
98
+ fdToken: undefined,
99
+ autoUpdateConfigs: undefined,
100
+ autoUpdateScripts: undefined,
101
+ scriptType: "base-scripts",
102
+ startMonitor: false,
103
+ };
104
+
105
+ for (let index = 0; index < args.length; index += 1) {
106
+ const arg = args[index];
107
+ switch (arg) {
108
+ case "--non-interactive":
109
+ options.nonInteractive = true;
110
+ break;
111
+ case "--company":
112
+ options.company = readRequiredFlagValue(args, index, "--company");
113
+ index += 1;
114
+ break;
115
+ case "--account":
116
+ case "--client":
117
+ options.account = readRequiredFlagValue(args, index, arg);
118
+ index += 1;
119
+ break;
120
+ case "--monitoring-configuration-id":
121
+ case "--id":
122
+ options.monitoringConfigurationId = readRequiredFlagValue(args, index, arg);
123
+ index += 1;
124
+ break;
125
+ case "--data-dir":
126
+ options.dataDir = readRequiredFlagValue(args, index, "--data-dir");
127
+ index += 1;
128
+ break;
129
+ case "--log-dir":
130
+ options.logDir = readRequiredFlagValue(args, index, "--log-dir");
131
+ index += 1;
132
+ break;
133
+ case "--oracle-home":
134
+ options.oracleHome = readRequiredFlagValue(args, index, "--oracle-home");
135
+ index += 1;
136
+ break;
137
+ case "--use-filedrop":
138
+ options.useFileDrop = readRequiredFlagValue(args, index, "--use-filedrop");
139
+ index += 1;
140
+ break;
141
+ case "--fdurl":
142
+ case "--fd-url":
143
+ options.fdUrl = readRequiredFlagValue(args, index, arg);
144
+ index += 1;
145
+ break;
146
+ case "--fdtoken":
147
+ case "--fd-token":
148
+ // This branch always throws; no break is needed.
149
+ throw new DataGatheringError(
150
+ `${arg} is not supported for setup because passing secrets in process arguments is unsafe. Configure the token separately after setup.`,
151
+ {
152
+ exitCode: DATA_GATHERING_EXIT_CODES.invalidInput,
153
+ type: "setup.invalid-input",
154
+ data: {
155
+ flag: arg,
156
+ },
157
+ },
158
+ );
159
+ case "--auto-update-configs":
160
+ options.autoUpdateConfigs = readRequiredFlagValue(args, index, "--auto-update-configs");
161
+ index += 1;
162
+ break;
163
+ case "--auto-update-scripts":
164
+ options.autoUpdateScripts = readRequiredFlagValue(args, index, "--auto-update-scripts");
165
+ index += 1;
166
+ break;
167
+ case "--script-type":
168
+ options.scriptType = readRequiredFlagValue(args, index, "--script-type");
169
+ index += 1;
170
+ break;
171
+ case "--start-monitor":
172
+ options.startMonitor = true;
173
+ break;
174
+ default:
175
+ throw new DataGatheringError(`Unknown setup flag: ${arg}`, {
176
+ exitCode: DATA_GATHERING_EXIT_CODES.invalidInput,
177
+ type: "setup.invalid-input",
178
+ data: {
179
+ flag: arg,
180
+ },
181
+ });
182
+ }
183
+ }
184
+
185
+ if (
186
+ options.useFileDrop !== undefined &&
187
+ !SUPPORTED_USE_FILEDROP_VALUES.has(options.useFileDrop)
188
+ ) {
189
+ throw new DataGatheringError(
190
+ `Unsupported USE_FILEDROP value '${options.useFileDrop}'. Expected one of ${JSON.stringify(Array.from(SUPPORTED_USE_FILEDROP_VALUES))}.`,
191
+ {
192
+ exitCode: DATA_GATHERING_EXIT_CODES.invalidInput,
193
+ type: "setup.invalid-input",
194
+ data: {
195
+ flag: "--use-filedrop",
196
+ value: options.useFileDrop,
197
+ },
198
+ },
199
+ );
200
+ }
201
+
202
+ return options;
203
+ }
204
+
205
+ function buildSelectionMap(items, keys) {
206
+ return items.map((item) => {
207
+ for (const key of keys) {
208
+ if (item?.[key] !== undefined && item?.[key] !== null && item?.[key] !== "") {
209
+ return {
210
+ label: `${item[key]}`,
211
+ value: `${item[key]}`,
212
+ item,
213
+ };
214
+ }
215
+ }
216
+
217
+ return {
218
+ label: JSON.stringify(item),
219
+ value: JSON.stringify(item),
220
+ item,
221
+ };
222
+ });
223
+ }
224
+
225
+ function valuesMatch(left, right) {
226
+ return `${left}` === `${right}`;
227
+ }
228
+
229
+ async function promptSelection(label, options) {
230
+ const rl = readline.createInterface({
231
+ input: process.stdin,
232
+ output: process.stderr,
233
+ });
234
+
235
+ try {
236
+ const currentValue = arguments[2];
237
+ const menu = options
238
+ .map((option, index) => {
239
+ const markedLabel = currentValue !== undefined && valuesMatch(option.value, currentValue)
240
+ ? `${option.label} *`
241
+ : option.label;
242
+ return ` ${index + 1}) ${markedLabel}`;
243
+ })
244
+ .join("\n");
245
+ const prompt = currentValue !== undefined
246
+ ? `${label}:\n${menu}\nChoose an option [1-${options.length}] or press Enter to keep current: `
247
+ : `${label}:\n${menu}\nChoose an option [1-${options.length}]: `;
248
+ const answer = await rl.question(prompt);
249
+ const trimmedAnswer = answer.trim();
250
+ if (trimmedAnswer === "" && currentValue !== undefined) {
251
+ const current = options.find((option) => valuesMatch(option.value, currentValue));
252
+ if (current) {
253
+ return current;
254
+ }
255
+ }
256
+ if (!/^\d+$/.test(trimmedAnswer)) {
257
+ throw new DataGatheringError(`Invalid ${label.toLowerCase()} selection`, {
258
+ exitCode: DATA_GATHERING_EXIT_CODES.invalidInput,
259
+ type: "setup.invalid-selection",
260
+ data: {
261
+ label,
262
+ value: answer,
263
+ },
264
+ });
265
+ }
266
+
267
+ const choice = Number.parseInt(trimmedAnswer, 10);
268
+ if (choice < 1 || choice > options.length) {
269
+ throw new DataGatheringError(`Invalid ${label.toLowerCase()} selection`, {
270
+ exitCode: DATA_GATHERING_EXIT_CODES.invalidInput,
271
+ type: "setup.invalid-selection",
272
+ data: {
273
+ label,
274
+ value: answer,
275
+ },
276
+ });
277
+ }
278
+
279
+ return options[choice - 1];
280
+ } finally {
281
+ rl.close();
282
+ }
283
+ }
284
+
285
+ async function chooseSelection({
286
+ label,
287
+ options,
288
+ currentValue,
289
+ currentValueSource = undefined,
290
+ nonInteractive,
291
+ ui,
292
+ logger,
293
+ }) {
294
+ const normalizedCurrent = currentValue === undefined || currentValue === null || currentValue === ""
295
+ ? undefined
296
+ : `${currentValue}`;
297
+ if (normalizedCurrent) {
298
+ const matched = options.find((option) => valuesMatch(option.value, normalizedCurrent));
299
+ if (!matched) {
300
+ if (currentValueSource === "explicit") {
301
+ throw new DataGatheringError(
302
+ `${label} '${normalizedCurrent}' is not available for setup`,
303
+ {
304
+ exitCode: DATA_GATHERING_EXIT_CODES.invalidInput,
305
+ type: "setup.invalid-selection",
306
+ data: {
307
+ label,
308
+ value: normalizedCurrent,
309
+ },
310
+ },
311
+ );
312
+ }
313
+ if (!nonInteractive) {
314
+ ui?.warn(`Stored default ${label.toLowerCase()} '${normalizedCurrent}' is no longer available. Please choose a new value.`);
315
+ } else {
316
+ ui?.warn(`Stored default ${label.toLowerCase()} '${normalizedCurrent}' is no longer available. Resolving a replacement automatically.`);
317
+ }
318
+ logger?.emit("setup.selection_default_invalid", {
319
+ label,
320
+ value: normalizedCurrent,
321
+ });
322
+ } else {
323
+ const shouldPromptForStoredDefault =
324
+ currentValueSource === "stored-default" && !nonInteractive && options.length > 1;
325
+ if (!shouldPromptForStoredDefault) {
326
+ return matched;
327
+ }
328
+ }
329
+ }
330
+
331
+ if (options.length === 0) {
332
+ throw new DataGatheringError(`No ${label.toLowerCase()} choices available`, {
333
+ exitCode: DATA_GATHERING_EXIT_CODES.invalidInput,
334
+ type: "setup.no-options",
335
+ data: {
336
+ label,
337
+ },
338
+ });
339
+ }
340
+
341
+ if (options.length === 1) {
342
+ ui?.info(`Only one ${label.toLowerCase()} is available. Using '${options[0].value}'.`);
343
+ logger?.emit("setup.selection_auto_selected", {
344
+ label,
345
+ reason: "single-option",
346
+ value: options[0].value,
347
+ });
348
+ return options[0];
349
+ }
350
+
351
+ if (nonInteractive) {
352
+ const selected = options[0];
353
+ ui?.warn(
354
+ `Multiple ${label.toLowerCase()} options are available. Using '${selected.value}' because setup is running non-interactively.`,
355
+ );
356
+ logger?.emit("setup.selection_auto_selected", {
357
+ label,
358
+ reason: "first-option-fallback",
359
+ value: selected.value,
360
+ options: options.map((option) => option.value),
361
+ });
362
+ return selected;
363
+ }
364
+
365
+ return promptSelection(label, options, normalizedCurrent);
366
+ }
367
+
368
+ function validateNonInteractiveOptions(options, effectiveNonInteractive = options.nonInteractive) {
369
+ if (!effectiveNonInteractive) {
370
+ return;
371
+ }
372
+ }
373
+
374
+ function readDefaultsFile() {
375
+ try {
376
+ const raw = fs.readFileSync(DEFAULTS_PATH, "utf8");
377
+ const parsed = JSON.parse(raw);
378
+ return {
379
+ company: parsed?.company ?? null,
380
+ account: parsed?.account ?? null,
381
+ monitoringConfiguration: parsed?.monitoringConfiguration ?? null,
382
+ };
383
+ } catch (error) {
384
+ if (error?.code === "ENOENT") {
385
+ return {
386
+ company: null,
387
+ account: null,
388
+ monitoringConfiguration: null,
389
+ };
390
+ }
391
+
392
+ throw new DataGatheringError("Failed to read defaults file", {
393
+ exitCode: DATA_GATHERING_EXIT_CODES.invalidInput,
394
+ type: "setup.defaults-read-failed",
395
+ data: {
396
+ defaultsPath: DEFAULTS_PATH,
397
+ reason: error?.message || `${error}`,
398
+ },
399
+ });
400
+ }
401
+ }
402
+
403
+ function normalizeDefaultValue(value) {
404
+ return value === undefined || value === null || value === "" ? undefined : `${value}`;
405
+ }
406
+
407
+ async function createDefaultMonitoringConfiguration(client, company, logger, ui) {
408
+ ui?.info(`No monitoring configuration exists for '${company}'. Creating a default monitoring configuration.`);
409
+ const created = await client.licenseManager.createMonitoringConfiguration(
410
+ company,
411
+ DEFAULT_MONITORING_CONFIGURATION_NAME,
412
+ );
413
+ logger?.emit("setup.monitoring_configuration_created", {
414
+ company,
415
+ monitoringConfigurationId: `${created.id}`,
416
+ configurationName: created.configurationName || DEFAULT_MONITORING_CONFIGURATION_NAME,
417
+ });
418
+ return created;
419
+ }
420
+
421
+ async function resolveSetupSelections(options, context = {}) {
422
+ const { logger, ui } = context;
423
+ const effectiveNonInteractive =
424
+ options.nonInteractive || !process.stdin.isTTY || !process.stdout.isTTY;
425
+ validateNonInteractiveOptions(options, effectiveNonInteractive);
426
+ const storedDefaults = readDefaultsFile();
427
+ const explicitCompany = normalizeDefaultValue(options.company);
428
+ const explicitAccount = normalizeDefaultValue(options.account);
429
+ const explicitMonitoringConfigurationId = normalizeDefaultValue(options.monitoringConfigurationId);
430
+ const storedCompany = normalizeDefaultValue(storedDefaults.company);
431
+ const preparedOptions = {
432
+ ...options,
433
+ company: explicitCompany || storedCompany,
434
+ account: explicitAccount,
435
+ monitoringConfigurationId: explicitMonitoringConfigurationId,
436
+ };
437
+
438
+ const client = await getOpsCompassClient();
439
+ const companies = await client.accounts.listCompanies();
440
+ const selectedCompany = await chooseSelection({
441
+ label: "Company",
442
+ options: buildSelectionMap(companies, ["company", "CUST_NAME", "name"]),
443
+ currentValue: preparedOptions.company,
444
+ currentValueSource: explicitCompany ? "explicit" : "stored-default",
445
+ nonInteractive: effectiveNonInteractive,
446
+ logger,
447
+ ui,
448
+ });
449
+
450
+ const companyMatchesDefault = normalizeDefaultValue(storedDefaults.company)
451
+ && valuesMatch(selectedCompany.value, storedDefaults.company);
452
+ const accountDefault = explicitAccount
453
+ || (companyMatchesDefault ? normalizeDefaultValue(storedDefaults.account) : undefined);
454
+ const monitoringConfigurationDefault = explicitMonitoringConfigurationId
455
+ || (companyMatchesDefault ? normalizeDefaultValue(storedDefaults.monitoringConfiguration) : undefined);
456
+
457
+ const accounts = (await client.accounts.listAccounts({
458
+ company: selectedCompany.value,
459
+ })) || [];
460
+ const mlssAccounts = accounts.filter(
461
+ (account) => account.cloudProvider === "mlss" || account.cloudProvider === undefined,
462
+ );
463
+ const selectedAccount = await chooseSelection({
464
+ label: "Account",
465
+ options: buildSelectionMap(mlssAccounts, ["cloudId", "CUST_TOKEN", "id", "name"]),
466
+ currentValue: accountDefault,
467
+ currentValueSource: explicitAccount ? "explicit" : "stored-default",
468
+ nonInteractive: effectiveNonInteractive,
469
+ logger,
470
+ ui,
471
+ });
472
+
473
+ let monitoringConfigurations =
474
+ (await client.licenseManager.listMonitoringConfigurations(selectedCompany.value)) || [];
475
+ if (monitoringConfigurations.length === 0) {
476
+ monitoringConfigurations = [
477
+ await createDefaultMonitoringConfiguration(client, selectedCompany.value, logger, ui),
478
+ ];
479
+ }
480
+ const selectedMonitoringConfiguration = await chooseSelection({
481
+ label: "Monitoring configuration",
482
+ options: buildSelectionMap(monitoringConfigurations, ["id", "configurationName", "name"]),
483
+ currentValue: monitoringConfigurationDefault,
484
+ currentValueSource: explicitMonitoringConfigurationId ? "explicit" : "stored-default",
485
+ nonInteractive: effectiveNonInteractive,
486
+ logger,
487
+ ui,
488
+ });
489
+
490
+ return {
491
+ company: selectedCompany,
492
+ account: selectedAccount,
493
+ monitoringConfiguration: selectedMonitoringConfiguration,
494
+ };
495
+ }
496
+
497
+ function normalizeSetupSelectionOptions(rawOptions) {
498
+ return {
499
+ nonInteractive: false,
500
+ ...rawOptions,
501
+ };
502
+ }
503
+
504
+ function resolveSetupPaths(options, selections) {
505
+ const company = selections.company.value;
506
+ const account = selections.account.value;
507
+ const configurationId = selections.monitoringConfiguration.value;
508
+ return {
509
+ lmBase: LEGACY_LMBASE_PATH,
510
+ dataDir: path.resolve(options.dataDir || path.join(opscompassHome, "data")),
511
+ logDir: path.resolve(options.logDir || path.join(opscompassHome, "log")),
512
+ configSaveDir: path.join(opscompassHome, "configs", company, account),
513
+ configFilePath: path.join(
514
+ opscompassHome,
515
+ "configs",
516
+ company,
517
+ account,
518
+ `${configurationId}-dgConfig.json`,
519
+ ),
520
+ };
521
+ }
522
+
523
+ function ensureDirectory(directoryPath) {
524
+ fs.mkdirSync(directoryPath, { recursive: true, mode: 0o700 });
525
+ }
526
+
527
+ function buildOlmDataParmsUpdate(options, paths) {
528
+ const olmUpdate = {
529
+ LMBASE: paths.lmBase,
530
+ DATA_DIR: paths.dataDir,
531
+ LOG_DIR: paths.logDir,
532
+ };
533
+
534
+ if (options.oracleHome !== undefined) {
535
+ olmUpdate.ORACLE_HOME = options.oracleHome;
536
+ }
537
+ if (options.useFileDrop !== undefined) {
538
+ olmUpdate.USE_FILEDROP = options.useFileDrop;
539
+ }
540
+ if (options.autoUpdateConfigs !== undefined) {
541
+ olmUpdate.OC_AUTOUPDATE_configs = options.autoUpdateConfigs;
542
+ }
543
+ if (options.autoUpdateScripts !== undefined) {
544
+ olmUpdate.OC_AUTOUPDATE_scripts = options.autoUpdateScripts;
545
+ }
546
+ if (options.fdUrl !== undefined) {
547
+ olmUpdate.FDURL = options.fdUrl;
548
+ }
549
+
550
+ return olmUpdate;
551
+ }
552
+
553
+ async function persistSetupState({ options, selections, paths }) {
554
+ ensureDirectory(paths.dataDir);
555
+ ensureDirectory(paths.logDir);
556
+ ensureDirectory(paths.configSaveDir);
557
+
558
+ await updateDefaults({
559
+ company: selections.company.value,
560
+ account: selections.account.value,
561
+ monitoringConfiguration: selections.monitoringConfiguration.value,
562
+ });
563
+
564
+ const olmState = writeOlmDataParms(buildOlmDataParmsUpdate(options, paths));
565
+ return {
566
+ defaultsPath: DEFAULTS_PATH,
567
+ olmDataParmsPath: olmState.filePath,
568
+ olmValues: olmState.values,
569
+ };
570
+ }
571
+
572
+ async function downloadScriptsForSetup(options, selections, logger) {
573
+ const client = await getOpsCompassClient();
574
+ await downloadScriptsToHome(
575
+ options.scriptType,
576
+ undefined,
577
+ selections.company.value,
578
+ client,
579
+ undefined,
580
+ createSetupScriptOutput(logger),
581
+ );
582
+ }
583
+
584
+ async function pullMonitoringConfiguration(selections, paths) {
585
+ const materialized = await materializeMonitoringConfiguration({
586
+ configId: Number.parseInt(selections.monitoringConfiguration.value, 10),
587
+ saveFile: paths.configFilePath,
588
+ silent: true,
589
+ overwrite: true,
590
+ output: createSetupConfigOutput(),
591
+ });
592
+
593
+ if (!materialized?.filePath) {
594
+ throw new DataGatheringError("Failed to save monitoring configuration locally", {
595
+ exitCode: DATA_GATHERING_EXIT_CODES.internalError,
596
+ type: "setup.config-save-failed",
597
+ data: {
598
+ configFilePath: paths.configFilePath,
599
+ },
600
+ });
601
+ }
602
+
603
+ return materialized.filePath;
604
+ }
605
+
606
+ function buildSetupResult({ selections, paths, persisted, validation, exitCode }) {
607
+ return {
608
+ company: selections.company.value,
609
+ account: selections.account.value,
610
+ monitoringConfigurationId: selections.monitoringConfiguration.value,
611
+ defaultsPath: persisted.defaultsPath,
612
+ olmDataParmsPath: persisted.olmDataParmsPath,
613
+ configFilePath: paths.configFilePath,
614
+ lmBase: paths.lmBase,
615
+ dataDir: paths.dataDir,
616
+ logDir: paths.logDir,
617
+ localRuntimeSettings: {
618
+ lmBase: persisted.olmValues.LMBASE,
619
+ useFileDrop: persisted.olmValues.USE_FILEDROP,
620
+ autoUpdateConfigs: persisted.olmValues.OC_AUTOUPDATE_configs,
621
+ autoUpdateScripts: persisted.olmValues.OC_AUTOUPDATE_scripts,
622
+ },
623
+ validation,
624
+ nextSteps: {
625
+ legacyInstaller: LEGACY_INSTALLER_PATH,
626
+ systemdExample:
627
+ "ExecStart=/usr/bin/opscompass data-gathering monitor start --directory /path/to/watch --pattern '*.json' --metadata-type network-discovery --destinations auto",
628
+ },
629
+ exitCode,
630
+ };
631
+ }
632
+
633
+ function buildSetupSummary(result) {
634
+ return {
635
+ company: result.company,
636
+ account: result.account,
637
+ monitoringConfigurationId: result.monitoringConfigurationId,
638
+ defaultsPath: result.defaultsPath,
639
+ olmDataParmsPath: result.olmDataParmsPath,
640
+ configFilePath: result.configFilePath,
641
+ lmBase: result.lmBase,
642
+ dataDir: result.dataDir,
643
+ logDir: result.logDir,
644
+ localRuntimeSettings: result.localRuntimeSettings,
645
+ validation: result.validation,
646
+ notes: [
647
+ "Local olm.dataParms OC_AUTOUPDATE_* settings are separate from auto-update fields stored in the saved monitoring configuration JSON.",
648
+ "Global override keys in olm.dataParms are preserved unless setup is given explicit override flags.",
649
+ ],
650
+ nextSteps: result.nextSteps,
651
+ exitCode: result.exitCode,
652
+ };
653
+ }
654
+
655
+ function printSetupSummary(result, ui = createDataGatheringUi()) {
656
+ const summary = buildSetupSummary(result);
657
+
658
+ ui.blank();
659
+ ui.section("Setup Complete");
660
+ if (result.exitCode === DATA_GATHERING_EXIT_CODES.success) {
661
+ ui.success("Data-gathering setup finished successfully.");
662
+ } else {
663
+ ui.warn("Data-gathering setup finished with follow-up actions required.");
664
+ }
665
+ ui.item("Company", summary.company);
666
+ ui.item("Account", summary.account);
667
+ ui.item("Monitoring configuration", summary.monitoringConfigurationId);
668
+ ui.item("Defaults", summary.defaultsPath);
669
+ ui.item("olm.dataParms", summary.olmDataParmsPath);
670
+ ui.item("Saved config", summary.configFilePath);
671
+ ui.item("LMBASE", summary.lmBase);
672
+ ui.item("Data directory", summary.dataDir);
673
+ ui.item("Log directory", summary.logDir);
674
+
675
+ ui.blank();
676
+ ui.section("Local Runtime Settings");
677
+ ui.item("LMBASE", summary.localRuntimeSettings.lmBase);
678
+ if (summary.localRuntimeSettings.useFileDrop !== undefined) {
679
+ ui.item("USE_FILEDROP", summary.localRuntimeSettings.useFileDrop);
680
+ }
681
+ if (summary.localRuntimeSettings.autoUpdateConfigs !== undefined) {
682
+ ui.item("OC_AUTOUPDATE_configs", summary.localRuntimeSettings.autoUpdateConfigs);
683
+ }
684
+ if (summary.localRuntimeSettings.autoUpdateScripts !== undefined) {
685
+ ui.item("OC_AUTOUPDATE_scripts", summary.localRuntimeSettings.autoUpdateScripts);
686
+ }
687
+
688
+ ui.blank();
689
+ ui.section("Notes");
690
+ for (const note of summary.notes) {
691
+ ui.note(note);
692
+ }
693
+
694
+ ui.blank();
695
+ ui.section("Next Steps");
696
+ if (!summary.validation?.ok) {
697
+ ui.item("Legacy installer", summary.nextSteps.legacyInstaller);
698
+ }
699
+ ui.item("Systemd example", summary.nextSteps.systemdExample);
700
+ }
701
+
702
+ async function runSetupWizard(args, logger) {
703
+ const ui = createDataGatheringUi();
704
+ const options = normalizeSetupSelectionOptions(parseSetupArgs(args));
705
+
706
+ if (!canReadStoredCredentials()) {
707
+ throw new DataGatheringError(
708
+ `You aren't logged in. Please run \`${cliCommand} login\` before running setup.`,
709
+ {
710
+ exitCode: DATA_GATHERING_EXIT_CODES.invalidInput,
711
+ type: "setup.login-required",
712
+ },
713
+ );
714
+ }
715
+
716
+ logger.emit("setup.started", {
717
+ nonInteractive: options.nonInteractive,
718
+ scriptType: options.scriptType,
719
+ });
720
+ ui.step(1, 5, "Resolve company, account, and monitoring configuration");
721
+
722
+ const selections = await resolveSetupSelections(options, { logger, ui });
723
+ logger.emit("setup.selection_resolved", {
724
+ company: selections.company.value,
725
+ account: selections.account.value,
726
+ monitoringConfigurationId: selections.monitoringConfiguration.value,
727
+ });
728
+
729
+ const paths = resolveSetupPaths(options, selections);
730
+ ui.step(2, 5, "Write defaults and local runtime files");
731
+ const persisted = await persistSetupState({ options, selections, paths });
732
+ logger.emit("setup.defaults_written", {
733
+ defaultsPath: persisted.defaultsPath,
734
+ company: selections.company.value,
735
+ account: selections.account.value,
736
+ monitoringConfigurationId: selections.monitoringConfiguration.value,
737
+ });
738
+ logger.emit("setup.olm_data_parms_written", {
739
+ path: OLM_DATA_PARMS_PATH,
740
+ lmBase: paths.lmBase,
741
+ dataDir: paths.dataDir,
742
+ logDir: paths.logDir,
743
+ useFileDrop: persisted.olmValues.USE_FILEDROP,
744
+ });
745
+
746
+ ui.step(3, 5, `Download ${options.scriptType} scripts`);
747
+ await downloadScriptsForSetup(options, selections, logger);
748
+ logger.emit("setup.scripts_downloaded", {
749
+ scriptType: options.scriptType,
750
+ });
751
+
752
+ ui.step(4, 5, "Save monitoring configuration locally");
753
+ const configFilePath = await pullMonitoringConfiguration(selections, paths);
754
+ logger.emit("setup.config_saved", {
755
+ configFilePath,
756
+ });
757
+
758
+ let validationResponse;
759
+ let exitCode = DATA_GATHERING_EXIT_CODES.success;
760
+ try {
761
+ ui.step(5, 5, "Validate local prerequisites");
762
+ validationResponse = await runValidateInstallCommand([], logger, { ui });
763
+ } catch (error) {
764
+ if (!(error instanceof DataGatheringError)) {
765
+ throw error;
766
+ }
767
+
768
+ exitCode = error.exitCode;
769
+ validationResponse = {
770
+ exitCode: error.exitCode,
771
+ result: {
772
+ ok: false,
773
+ missing: error.data.missingDependencies || [],
774
+ remediation:
775
+ `Install the required prerequisites, then rerun setup or validation. Legacy installer reference: ${LEGACY_INSTALLER_PATH}`,
776
+ },
777
+ };
778
+ }
779
+
780
+ const result = buildSetupResult({
781
+ selections,
782
+ paths,
783
+ persisted,
784
+ validation: validationResponse.result,
785
+ exitCode,
786
+ });
787
+
788
+ logger.emit("setup.completed", {
789
+ status: exitCode === DATA_GATHERING_EXIT_CODES.success ? "success" : "failed",
790
+ exitCode,
791
+ company: result.company,
792
+ account: result.account,
793
+ monitoringConfigurationId: result.monitoringConfigurationId,
794
+ configFilePath: result.configFilePath,
795
+ dataDir: result.dataDir,
796
+ logDir: result.logDir,
797
+ startMonitorSuggested: true,
798
+ systemdExample: result.nextSteps.systemdExample,
799
+ });
800
+
801
+ printSetupSummary(result, ui);
802
+
803
+ return {
804
+ exitCode,
805
+ result,
806
+ };
807
+ }
808
+
809
+ export {
810
+ DEFAULT_AUTOUPDATE_CONFIGS,
811
+ DEFAULT_AUTOUPDATE_SCRIPTS,
812
+ DEFAULT_USE_FILEDROP,
813
+ SUPPORTED_USE_FILEDROP_VALUES,
814
+ buildOlmDataParmsUpdate,
815
+ buildSelectionMap,
816
+ buildSetupSummary,
817
+ buildSetupResult,
818
+ chooseSelection,
819
+ normalizeSetupSelectionOptions,
820
+ parseSetupArgs,
821
+ printSetupSummary,
822
+ resolveSetupPaths,
823
+ resolveSetupSelections,
824
+ runSetupWizard,
825
+ validateNonInteractiveOptions,
826
+ };