const express = require('express') const bodyParser = require('body-parser') const path = require('path') const fs = require('fs') const fsPromises = fs.promises const app = express() let apps = process.env.APPS ? JSON.parse(process.env.APPS) : ['highlight-termbin', 'dyndns', 'distrib-ipfs'] let sock = process.env.SOCKET || '/tmp/serve-lunasqu.ee.t.sock' app.enable('trust proxy', 1) app.disable('x-powered-by') app.use(bodyParser.urlencoded({ extended: false })) app.use(bodyParser.json()) function requireNoCache (file) { let fullPath = path.resolve(file) let data = require(fullPath) if (require.cache && require.cache[fullPath]) { delete require.cache[fullPath] } return data } async function enableApp (name) { let papp = path.join(__dirname, 'applications', name) await fsPromises.access(papp, fs.constants.F_OK) let runner = requireNoCache(papp) if (!runner) throw new Error('No such application.') let router = await runner() app.use('/' + name, router) } async function init () { for (let i in apps) { let papp = apps[i] try { await enableApp(papp) console.log(' =>', papp, 'was enabled successfully.') } catch (e) { console.error('Failed to start application', papp) console.error(e.stack) } } try { await fsPromises.unlink(sock) } catch (e) {} app.listen(sock, function () { console.log('Started server on', sock) }) } module.exports = init