summaryrefslogtreecommitdiffstats
path: root/cholerab/knut/index.js
blob: b8951f1d93fb043e6b0b60380818a03f63c1e880 (plain)
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
#! /usr/bin/env node

var host = process.env.host || '127.0.0.1';
var port = Number(process.env.port) || 42101;

var pipe = '/tmp/krebscode.painload.cholerab.ttycnser.' + process.env.LOGNAME;

var fs = require('fs');
var http = require('http');
var slurp = require('./src/io/slurp');
var spawn = require('child_process').spawn;

var plugs = process.argv.slice(2);

if (plugs.length === 0) {
  console.error('Error 1: You are made of stupid!'
      + '\nPro-Tip: '
      + require('path').basename(process.argv[1]) + ' PLUG'
      + ' # PLUG ∈ {'
      + require('fs').readdirSync(__dirname + '/plugs').join(',')
      + '}^n, n ≥ 1');
  process.exit(23);
};

http.createServer(function (req, res) {
  return slurp(req, function (data) {
    try {
      var message = JSON.parse(data);
    } catch (exn) {
      console.error(exn.stack);
    };
    if (message) {
      plugs.forEach(function (plug) {

        var env = JSON.parse(JSON.stringify(process.env));
        Object.keys(message).forEach(function (key) {
          env[key] = message[key];
        });

        var child = spawn(__dirname + '/plugs/' + plug + '/index', [], {
          env: env
        });

        child.stdout.on('data', function (data) {
          console.log(plug, 'stdout:', data.toString());
        });

        child.stderr.on('data', function (data) {
          console.log(plug, 'stderr:', data.toString());
        });

        child.on('exit', function (code) {
          console.log(plug, 'exit:', code);
          if (code === 0) {
            res.writeHead(200, { 'Content-Length': 0 });
            res.end();
          } else {
            res.writeHead(500, { 'Content-Length': 0 });
            res.end();
          };
        });

      });
    } else {
      res.writeHead(400, 'You are made of stupid!', {
        'Content-Length': 0
      });
      res.end();
    };
  });
}).listen(port, host, function () {
  console.log('Serving HTTP on', host, 'port', port);
});