-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup.js
More file actions
425 lines (348 loc) · 12.4 KB
/
Copy pathsetup.js
File metadata and controls
425 lines (348 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
const fs = require("node:fs");
const path = require("node:path");
const { spawnSync } = require("node:child_process");
const readline = require("node:readline/promises");
const { stdin, stdout } = require("node:process");
const { jsonc } = require("jsonc");
const ENV_FILE_PATH = path.resolve(__dirname, "env.json");
const EXAMPLE_ENV_FILE_PATH = path.resolve(__dirname, "example.env.jsonc");
const ECOSYSTEM_FILE_PATH = path.resolve(__dirname, "ecosystem.config.js");
const PM2_APP_NAME = "mongocord";
const REQUIRED_FIELDS = [
"token",
"clientId",
"mongoUri",
"devAdmins"
];
function readJsoncFile(filePath) {
try {
return jsonc.parse(fs.readFileSync(filePath, "utf8"));
}
catch (error) {
throw new Error(`Failed to read ${path.basename(filePath)}: ${error.message}`);
}
}
function readExistingEnv() {
if (!fs.existsSync(ENV_FILE_PATH)) {
return {};
}
try {
return jsonc.parse(fs.readFileSync(ENV_FILE_PATH, "utf8")) || {};
}
catch (error) {
console.warn(`Could not parse existing env.json (${error.message}). Starting with blank values.`);
return {};
}
}
function validateEnvShape(env) {
for (const field of REQUIRED_FIELDS) {
if (!(field in env)) {
throw new Error(`Missing required environment field "${field}" in env.json.`);
}
}
if (!Array.isArray(env.devAdmins) || env.devAdmins.length === 0) {
throw new Error("env.json field \"devAdmins\" must be a non-empty array of Discord user IDs.");
}
}
function parseDevAdmins(value) {
return [...new Set(
String(value || "")
.split(/[\s,]+/)
.map(entry => entry.trim())
.filter(Boolean)
)];
}
async function askField(rl, label, {
defaultValue = "",
required = false,
parser = value => value,
hideDefault = false
} = {}) {
while (true) {
const hasDefault = defaultValue != null && String(defaultValue).length > 0;
const suffix = hasDefault
? (hideDefault ? " [current set]" : ` [${String(defaultValue)}]`)
: "";
const answer = (await rl.question(`${label}${suffix}: `)).trim();
const rawValue = answer || (hasDefault ? String(defaultValue) : "");
const parsedValue = parser(rawValue);
const isMissing = Array.isArray(parsedValue)
? parsedValue.length === 0
: !String(parsedValue).trim();
if (required && isMissing) {
console.log(`"${label}" is required.`);
continue;
}
return parsedValue;
}
}
async function askYesNo(rl, prompt, defaultYes = false) {
const suffix = defaultYes ? " [Y/n]" : " [y/N]";
while (true) {
const answer = (await rl.question(`${prompt}${suffix}: `)).trim().toLowerCase();
if (!answer) {
return defaultYes;
}
if (["y", "yes"].includes(answer)) {
return true;
}
if (["n", "no"].includes(answer)) {
return false;
}
console.log("Please answer yes or no.");
}
}
function runCommand(command, args, inheritOutput = true) {
return spawnSync(command, args, {
cwd: __dirname,
shell: process.platform === "win32",
stdio: inheritOutput ? "inherit" : "pipe",
encoding: "utf8"
});
}
function getLocalPm2Command() {
return path.join(__dirname, "node_modules", ".bin", process.platform === "win32" ? "pm2.cmd" : "pm2");
}
function getPm2Command() {
const globalResult = runCommand("pm2", ["-v"], false);
if (globalResult.status === 0) {
return "pm2";
}
const localCommand = getLocalPm2Command();
if (!fs.existsSync(localCommand)) {
return null;
}
const localResult = runCommand(localCommand, ["-v"], false);
return localResult.status === 0 ? localCommand : null;
}
function hasPm2() {
return Boolean(getPm2Command());
}
function commandExists(command) {
const lookup = process.platform === "win32" ? "where" : "which";
const result = runCommand(lookup, [command], false);
return result.status === 0;
}
function getPm2StartupCommand() {
if (commandExists("pm2-startup")) {
return "pm2-startup";
}
if (process.platform !== "win32") {
return null;
}
const appData = process.env.APPDATA;
if (!appData) {
return null;
}
const candidate = path.join(appData, "npm", "pm2-startup.cmd");
if (fs.existsSync(candidate)) {
return candidate;
}
return null;
}
function configurePm2StartupForBoot(pm2Command) {
if (process.platform === "win32") {
console.log("Windows detected. Configuring startup with pm2-windows-startup.");
let startupCommand = getPm2StartupCommand();
if (!startupCommand) {
console.log("pm2-windows-startup is not installed. Installing it globally now...");
const installHelperResult = runCommand("npm", ["install", "-g", "pm2-windows-startup"]);
if (installHelperResult.status !== 0) {
console.log("Could not install pm2-windows-startup automatically.");
return false;
}
startupCommand = getPm2StartupCommand();
}
if (!startupCommand) {
console.log("Could not locate pm2-startup after installation.");
return false;
}
const startupResult = runCommand(startupCommand, ["install"]);
if (startupResult.status !== 0) {
console.log("pm2-startup install did not complete. Try running setup in an elevated shell.");
return false;
}
return true;
}
const startupResult = runCommand(pm2Command, ["startup"]);
if (startupResult.status !== 0) {
console.log("pm2 startup did not complete. Try running it in an elevated shell.");
return false;
}
return true;
}
function registerSlashCommands() {
console.log("Registering Discord slash commands...");
const result = runCommand("node", ["launchCommands.js"]);
return result.status === 0;
}
async function installPm2(rl) {
const installResult = runCommand("npm", ["install", "-g", "pm2"]);
let pm2Command = getPm2Command();
if (installResult.status === 0 && pm2Command) {
return pm2Command;
}
if (process.platform !== "win32") {
if (commandExists("sudo")) {
const shouldInstallWithSudo = await askYesNo(
rl,
"Global install failed. Retry with sudo (will prompt for your password)",
true
);
if (shouldInstallWithSudo) {
const sudoInstallResult = runCommand("sudo", ["npm", "install", "-g", "pm2"]);
pm2Command = getPm2Command();
if (sudoInstallResult.status === 0 && pm2Command) {
return pm2Command;
}
}
}
const shouldInstallLocal = await askYesNo(
rl,
"Install PM2 locally in this project instead (no root required)",
true
);
if (shouldInstallLocal) {
const localInstallResult = runCommand("npm", ["install", "--no-save", "pm2"]);
pm2Command = getPm2Command();
if (localInstallResult.status === 0 && pm2Command) {
console.log("PM2 installed locally. Use npm scripts or npx pm2 for future PM2 commands.");
return pm2Command;
}
}
}
return null;
}
async function configurePm2(rl) {
const summary = {
usedPm2: false,
available: false,
started: false,
startupEnabled: false
};
const wantsPm2 = await askYesNo(rl, "Configure PM2 now", true);
if (!wantsPm2) {
return summary;
}
summary.usedPm2 = true;
let pm2Command = getPm2Command();
if (!pm2Command) {
console.log("PM2 was not found in PATH.");
const shouldInstall = await askYesNo(rl, "Install PM2 globally with npm install -g pm2", true);
if (!shouldInstall) {
console.log("Skipping PM2 setup.");
return summary;
}
pm2Command = await installPm2(rl);
if (!pm2Command) {
console.log("Could not install PM2 automatically. Install it manually and rerun setup if needed.");
return summary;
}
}
summary.available = true;
const shouldStart = await askYesNo(rl, "Start or restart Mongocord in PM2 now", true);
if (shouldStart) {
let startResult = runCommand(pm2Command, ["startOrRestart", ECOSYSTEM_FILE_PATH, "--only", PM2_APP_NAME]);
if (startResult.status !== 0) {
startResult = runCommand(pm2Command, ["start", ECOSYSTEM_FILE_PATH, "--only", PM2_APP_NAME]);
}
if (startResult.status !== 0) {
console.log("PM2 failed to start the bot. You can try again manually later.");
return summary;
}
summary.started = true;
}
const shouldEnableStartup = await askYesNo(
rl,
"Enable startup on boot (runs pm2 startup and pm2 save)",
true
);
if (shouldEnableStartup) {
summary.startupEnabled = configurePm2StartupForBoot(pm2Command);
const saveResult = runCommand(pm2Command, ["save"]);
if (saveResult.status !== 0) {
console.log("pm2 save failed. Run pm2 save manually after PM2 is configured.");
}
}
return summary;
}
async function main() {
if (!fs.existsSync(EXAMPLE_ENV_FILE_PATH)) {
throw new Error("example.env.jsonc is missing.");
}
const template = readJsoncFile(EXAMPLE_ENV_FILE_PATH);
const existing = readExistingEnv();
const rl = readline.createInterface({ input: stdin, output: stdout });
try {
console.log("Mongocord setup");
if (fs.existsSync(ENV_FILE_PATH)) {
console.log("Existing env.json detected. Leave a field blank to keep its current value.");
}
const token = await askField(rl, "Discord bot token", {
defaultValue: existing.token,
required: true,
hideDefault: true
});
const clientId = await askField(rl, "Discord application client ID", {
defaultValue: existing.clientId,
required: true
});
const mongoUri = await askField(rl, "MongoDB URI", {
defaultValue: existing.mongoUri,
required: true,
hideDefault: true
});
const stateDatabaseName = await askField(rl, "State database name (optional)", {
defaultValue: existing.stateDatabaseName
});
const devAdmins = await askField(rl, "Dev admin Discord user IDs (comma or space separated)", {
defaultValue: Array.isArray(existing.devAdmins) ? existing.devAdmins.join(", ") : "",
required: true,
parser: parseDevAdmins
});
const env = {
token,
clientId,
mongoUri,
...(stateDatabaseName ? { stateDatabaseName } : {}),
devAdmins
};
validateEnvShape(env);
fs.writeFileSync(ENV_FILE_PATH, `${JSON.stringify(env, null, 4)}\n`, "utf8");
console.log("Wrote env.json successfully.");
if (!template || typeof template !== "object") {
console.warn("Warning: example.env.jsonc could not be parsed into an object.");
}
const commandsRegistered = registerSlashCommands();
const pm2Summary = await configurePm2(rl);
console.log("Setup complete.");
if (commandsRegistered) {
console.log("Discord slash commands are registered.");
}
else {
console.log("Slash command registration failed. Run npm run register manually.");
}
if (pm2Summary.started) {
console.log("Mongocord is running under PM2.");
}
else if (pm2Summary.available) {
console.log("PM2 is configured, but startup was not triggered in this run.");
}
else if (pm2Summary.usedPm2) {
console.log("PM2 setup was requested, but PM2 is still not installed/configured.");
}
else {
console.log("PM2 setup was skipped.");
}
if (pm2Summary.startupEnabled) {
console.log("Startup on boot is enabled.");
}
}
finally {
rl.close();
}
}
main().catch(error => {
console.error(error.message || error);
process.exitCode = 1;
});