import fs from 'fs';
import os from 'os';
import path from 'path';
import http from 'http';
import Koa from 'koa';
import Body from 'koa-body';
import Router from 'koa-router';
import cache from 'koa-static-cache';
import nunjucks from 'nunjucks';
import mongodb from 'mongodb';
import parse from 'yargs-parser';
const argv = parse(process.argv.slice(2));
class Loader {
getSource(name: string) { // eslint-disable-line class-methods-use-this
return {
src: `
{{ _('Setup') }}
`,
path: name,
noCache: false,
};
}
}
const env = new nunjucks.Environment(new Loader(), { autoescape: true, trimBlocks: true });
function render(name) {
return new Promise((resolve, reject) => {
env.render(name, {
_: (str) => str,
}, (err, res) => {
if (err) reject(err);
else resolve(res);
});
});
}
export function load() {
const app = new Koa();
const server = http.createServer(app.callback());
const router = new Router();
app.keys = ['Hydro'];
app.use(cache(path.join(os.tmpdir(), 'hydro', 'public'), {
maxAge: 365 * 24 * 60 * 60,
}));
app.use(Body());
router.get('/', async (ctx) => {
ctx.body = await render('setup.html');
ctx.response.type = 'text/html';
});
const listenPort = argv.port || 8888;
router.post('/', async (ctx) => {
const {
host, port, name, username, password,
} = ctx.request.body;
let mongourl = 'mongodb://';
if (username) mongourl += `${username}:${password}@`;
mongourl += `${host}:${port}/${name}`;
try {
const Database = await mongodb.MongoClient.connect(mongourl, {
useNewUrlParser: true, useUnifiedTopology: true,
});
const db = Database.db(name);
await Promise.all([
db.collection('system').updateOne(
{ _id: 'server.host' },
{ $set: { value: ctx.request.host } },
{ upsert: true },
),
db.collection('system').updateOne(
{ _id: 'server.hostname' },
{ $set: { value: ctx.request.hostname } },
{ upsert: true },
),
db.collection('system').updateOne(
{ _id: 'server.url' },
{ $set: { value: ctx.request.href } },
{ upsert: true },
),
db.collection('system').updateOne(
{ _id: 'server.port' },
{ $set: { value: listenPort } },
{ upsert: true },
),
]);
fs.writeFileSync(path.resolve(process.cwd(), 'config.json'), JSON.stringify({
host, port, name, username, password,
}));
ctx.body = `This page will reload in 3 secs.
`;
setTimeout(() => process.exit(0), 500);
} catch (e) {
ctx.body = `Error connecting to database: ${e.message}\n${e.stack}`;
}
});
app.use(router.routes()).use(router.allowedMethods());
server.listen(listenPort);
console.log('Server listening at:', listenPort);
}