-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathInstallDroidScripts.js
More file actions
298 lines (268 loc) · 8.78 KB
/
Copy pathInstallDroidScripts.js
File metadata and controls
298 lines (268 loc) · 8.78 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
const HOME = "home";
const DEFAULT_BASE_URL = "https://raw.githubusercontent.com/TheDroidYourLookingFor/BitBurner-Scripts/main/";
// Keep this list in repository-relative form. Files are downloaded from GitHub
// and installed at the same absolute paths on home.
const INSTALL_FILES = [
"droid-autopilot.js",
"droid-backdoors.js",
"droid-batch.js",
"droid-casino.js",
"droid-cloud.js",
"droid-contracts.js",
"droid-crime.js",
"droid-custom-stats.js",
"droid-daemon.js",
"droid-darknet.js",
"droid-deploy.js",
"droid-faction.js",
"droid-gangs.js",
"droid-gym.js",
"droid-hacknet.js",
"droid-hashnet.js",
"droid-loop.js",
"droid-poll-server.js",
"droid-prep.js",
"droid-programs.js",
"droid-root.js",
"droid-start.js",
"droid-status.js",
"droid-stock.js",
"droid-stop.js",
"droid-xp-launcher.js",
"droid-xp.js",
"ServerExplorer.js",
"lib/allocator.js",
"lib/batcher-v3.js",
"lib/batcher.js",
"lib/common.js",
"lib/formulas.js",
"lib/network.js",
"lib/root-network.js",
"workers/grow-loop.js",
"workers/grow.js",
"workers/hack-loop.js",
"workers/hack.js",
"workers/weaken-loop.js",
"workers/weaken.js",
"workers/xp-grow.js",
"workers/xp-hack.js",
"workers/xp-weaken.js",
"InstallDroidScripts.js",
];
function absolutePath(filename) {
return `/${String(filename).replace(/^\/+/, "")}`;
}
function comparablePath(filename) {
return absolutePath(filename).toLowerCase();
}
function normalizedBaseUrl(value) {
const url = String(value || DEFAULT_BASE_URL).trim();
return url.endsWith("/") ? url : `${url}/`;
}
function scanAll(ns) {
const seen = new Set([HOME]);
const queue = [HOME];
for (let index = 0; index < queue.length; index += 1) {
for (const neighbor of ns.scan(queue[index])) {
if (seen.has(neighbor)) continue;
seen.add(neighbor);
queue.push(neighbor);
}
}
return queue;
}
function validDownload(contents) {
const text = String(contents ?? "").trim();
if (!text) return false;
if (/^(404|400):/i.test(text)) return false;
if (/^<!doctype html/i.test(text) || /^<html[\s>]/i.test(text)) return false;
return true;
}
async function stageDownloads(ns, baseUrl, stagePrefix) {
const staged = [];
for (let index = 0; index < INSTALL_FILES.length; index += 1) {
const filename = INSTALL_FILES[index];
const temporaryFile = `${stagePrefix}${index}.txt`;
const source = `${baseUrl}${filename}?cache=${Date.now()}-${index}`;
ns.rm(temporaryFile, HOME);
let downloaded = false;
try {
downloaded = await ns.wget(source, temporaryFile, HOME);
} catch (error) {
throw new Error(`${filename}: ${String(error)}`);
}
const contents = ns.read(temporaryFile);
if (!downloaded || !validDownload(contents)) {
ns.rm(temporaryFile, HOME);
throw new Error(`${filename}: GitHub returned no usable script`);
}
staged.push({ filename, temporaryFile });
const completed = index + 1;
if (completed === 1 || completed % 5 === 0 || completed === INSTALL_FILES.length) {
ns.tprintf(`Staged ${completed}/${INSTALL_FILES.length} files...`);
}
}
return staged;
}
function cleanStagingFiles(ns, stagePrefix) {
for (const filename of ns.ls(HOME, stagePrefix.replace(/^\/+/, ""))) {
try { ns.rm(filename, HOME); } catch { /* best-effort temporary-file cleanup */ }
}
}
function stopInstalledProcesses(ns) {
const installed = new Set(INSTALL_FILES.map(comparablePath));
let stopped = 0;
for (const host of scanAll(ns)) {
for (const process of ns.ps(host)) {
if (process.pid === ns.pid || !installed.has(comparablePath(process.filename))) continue;
try {
if (ns.kill(process.pid)) stopped += 1;
} catch {
// A short-lived worker may finish between ps() and kill().
}
}
}
return stopped;
}
function installStagedFiles(ns, staged) {
let installed = 0;
for (const { filename, temporaryFile } of staged) {
const contents = ns.read(temporaryFile);
if (!validDownload(contents)) throw new Error(`Staged copy of ${filename} is invalid`);
ns.write(absolutePath(filename), contents, "w");
installed += 1;
}
return installed;
}
async function removeLegacyInstall(ns) {
const legacyFiles = ns.ls(HOME).filter((filename) => {
const normalized = String(filename).replace(/^\/+/, "");
return normalized.startsWith("TheDroid/");
});
if (legacyFiles.length === 0) return { removed: 0, stopped: 0 };
const confirmed = await ns.prompt(
`Remove ${legacyFiles.length} file(s) from the old /TheDroid/ installation?`,
{ type: "boolean" },
);
if (!confirmed) return { removed: 0, stopped: 0 };
let stopped = 0;
for (const host of scanAll(ns)) {
for (const process of ns.ps(host)) {
const filename = comparablePath(process.filename);
if (process.pid === ns.pid || !filename.startsWith("/thedroid/")) continue;
try {
if (ns.kill(process.pid)) stopped += 1;
} catch {
// A legacy worker may finish between ps() and kill().
}
}
}
let removed = 0;
for (const filename of legacyFiles) {
try {
if (ns.rm(filename, HOME)) removed += 1;
} catch {
// Report the final count; a locked file can be removed on the next run.
}
}
return { removed, stopped };
}
function terminalInput() {
return /** @type {HTMLInputElement | null} */ (
globalThis["document"]?.getElementById("terminal-input") ?? null
);
}
function reactProps(element) {
const reactElement = /** @type {HTMLInputElement & Record<string, any>} */ (element);
const key = Object.keys(reactElement).find((candidate) => candidate.startsWith("__reactProps"));
return key ? reactElement[key] : null;
}
async function createDroidAlias(ns) {
const input = terminalInput();
if (!input) return false;
const props = reactProps(input);
if (!props || typeof props.onChange !== "function") return false;
input.value = 'alias -g Droid="run /droid-start.js"';
props.onChange({ target: input });
await ns.sleep(0);
const updatedInput = terminalInput();
const updatedProps = updatedInput ? reactProps(updatedInput) : null;
if (!updatedInput || !updatedProps || typeof updatedProps.onKeyDown !== "function") return false;
updatedProps.onKeyDown({
key: "Enter",
code: "Enter",
keyCode: 13,
which: 13,
target: updatedInput,
currentTarget: updatedInput,
preventDefault: () => null,
stopPropagation: () => null,
});
return true;
}
/** @param {NS} ns */
export async function main(ns) {
ns.disableLog("ALL");
const flags = ns.flags([
["base-url", DEFAULT_BASE_URL],
["keep-legacy", false],
["no-alias", false],
["help", false],
]);
if (flags.help) {
ns.tprint([
"Droid Reboot installer/updater",
"",
"Usage: run /InstallDroidScripts.js [options]",
"",
" --base-url URL Download from another raw GitHub directory",
" --keep-legacy Do not offer to remove the old /TheDroid/ directory",
" --no-alias Do not create the global Droid terminal alias",
" --help Show this help",
].join("\n"));
return;
}
if (ns.getHostname() !== HOME) {
ns.tprint("ERROR: Run /InstallDroidScripts.js from home.");
return;
}
const baseUrl = normalizedBaseUrl(flags["base-url"]);
const stagePrefix = `/temp-droid-installer-${Date.now()}-`;
ns.tprintf(`Droid Reboot installer: downloading ${INSTALL_FILES.length} files from ${baseUrl}`);
let staged = [];
try {
staged = await stageDownloads(ns, baseUrl, stagePrefix);
} catch (error) {
cleanStagingFiles(ns, stagePrefix);
ns.tprintf(`INSTALL ABORTED: ${String(error)}`);
ns.tprint("No installed Droid scripts were changed. Check the repository, branch, and network connection, then retry.");
return;
}
let installed = 0;
let stopped = 0;
try {
stopped = stopInstalledProcesses(ns);
installed = installStagedFiles(ns, staged);
} catch (error) {
ns.tprintf(`INSTALL FAILED while writing files: ${String(error)}`);
ns.tprint("Run the installer again before starting Droid Reboot.");
return;
} finally {
cleanStagingFiles(ns, stagePrefix);
}
const legacy = flags["keep-legacy"]
? { removed: 0, stopped: 0 }
: await removeLegacyInstall(ns);
stopped += legacy.stopped;
let aliasCreated = false;
if (!flags["no-alias"]) {
try { aliasCreated = await createDroidAlias(ns); } catch { /* alias is optional */ }
}
ns.tprint("");
ns.tprintf(`Install complete: ${installed}/${INSTALL_FILES.length} files updated; ${stopped} running Droid process(es) stopped.`);
if (legacy.removed > 0) ns.tprintf(`Removed ${legacy.removed} legacy /TheDroid/ file(s).`);
ns.tprint(aliasCreated
? "Start with: Droid"
: "Start with: run /droid-start.js");
ns.tprint("The installer does not restart automation automatically after an update.");
}