-
Notifications
You must be signed in to change notification settings - Fork 0
/
command.js
107 lines (100 loc) · 2.98 KB
/
command.js
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
#!/usr/bin/env node
const program = require("commander");
const pm2 = require("pm2");
const crypto = require("crypto");
const path = require("path");
const config = {
jwt_secret: crypto.randomBytes(64).toString("hex"),
db_uri: "postgresql://ctf@localhost:5432/ctf",
port: 3000,
env: {},
};
function start(callback) {
const env = {
PORT: config.port,
DATABASE_URI: config.db_uri,
SECRET_KEY: config.jwt_secret,
CORS_ORIGIN: config.cors_origin,
};
Object.assign(env, config.env);
if (config.plugin_folder) {
env.PLUGIN_FOLDER = config.plugin_folder;
}
pm2.start(
path.join(__dirname, "index.js"),
{env: env, name: "ctf"},
function (err, proc) {
if (err && err.message === "Script already launched") {
console.log("Error: ctfjs already running");
} else if (err) {
throw err;
}
pm2.disconnect(callback);
}
);
}
function stop(callback) {
pm2.delete("ctf", function (err, proc) {
if (err) {
throw err;
}
pm2.disconnect(callback);
});
}
program
.command("start")
.option("-r, --restart", "restart if already running")
.option("-s, --secret-key <secret_key>", "secret key")
.option("-d, --database <database_uri>", "database URI")
.option("-p, --port <port>", "port to listen on")
.option(
"-o, --cors-origin <cors_origin>",
"comma separated list of origins for CORS header"
)
.option("-f, --plugin-folder <plugin_folder>", "plugins folder")
.option(
"-e, --environment <environment_var>s",
"environment variables in the form <key>=<val> separated by semicolons"
)
.action(function (command) {
if (command.secretKey) {
config.jwt_secret = command.secretKey;
}
if (command.database) {
config.db_uri = command.database;
}
if (command.port) {
config.port = command.port;
}
if (command.pluginFolder) {
config.plugin_folder = path.resolve(command.pluginFolder);
}
if (command.corsOrigin) {
config.cors_origin = command.corsOrigin;
}
if (command.environment) {
command.environment = command.environment.split(";");
for (let i = 0; i < command.environment.length; i++) {
const env = command.environment[i].split(/^([^=]+)=/);
env.splice(0, 1);
config.env[env[0]] = env[1];
}
}
if (command.restart) {
stop(function () {
start(function () {
process.exit(0);
});
});
} else {
start(function () {
process.exit(0);
});
}
});
program.command("stop").action(function (command) {
stop(function () {
process.exit(0);
});
});
program.parse(process.argv);