"use strict";

var zlib = require("zlib");

var cors = require("cors"),
    express = require("express");

var SyslogFilter = require("./syslog-filter");

module.exports = function(source) {
  var app = express();

  app.disable('x-powered-by');

  app.use(cors());

  app.get("/:ps(\\w*)?", function(req, res, next) {
    res.header("Content-Type", "text/plain");

    // compression
    var acceptEncoding = req.headers["accept-encoding"] || "",
        options = {
          flush: zlib.Z_PARTIAL_FLUSH
        };

    var src;

    if (req.params.ps) {
      // process name was provided
      src = source.pipe(new SyslogFilter(req.params.ps));
    } else {
      src = source;
    }

    if (acceptEncoding.indexOf("gzip") >= 0) {
      res.header("Content-Encoding", "gzip");
      return src.pipe(zlib.createGzip(options)).pipe(res);
    }

    if (acceptEncoding.indexOf("deflate") >= 0) {
      res.header("Content-Encoding", "deflate");
      return src.pipe(zlib.createDeflate(options)).pipe(res);
    }

    return source.pipe(res);
  });

  return app;
};

@@ -12,16 +12,48 @@
 %22;%0A%0Avar 
+stream = require(%22stream%22),%0A    
 zlib = r
@@ -206,22 +206,21 @@
 unction(
-source
+nexus
 ) %7B%0A  va
@@ -551,18 +551,46 @@
    var s
-rc
+ink = new stream.PassThrough()
 ;%0A%0A    i
@@ -650,28 +650,78 @@
 d%0A      
-src = source
+console.log(%22Filtering for%22, req.params.ps);%0A      sink = sink
 .pipe(ne
@@ -761,41 +761,27 @@
    %7D
- else %7B%0A      src = source;%0A    %7D
+%0A%0A    var response;
 %0A%0A  
@@ -873,34 +873,35 @@
 ip%22);%0A      
-return src
+sink = sink
 .pipe(zlib.c
@@ -919,38 +919,28 @@
 ptions))
-.pipe(res)
 ;%0A    %7D
-%0A%0A   
+ else
  if (acc
@@ -1037,18 +1037,19 @@
     
-return src
+sink = sink
 .pip
@@ -1078,16 +1078,137 @@
 ptions))
+;%0A    %7D%0A%0A    // don't reassign to sink--we need the stream that's actually plugged into%0A    // nexus%0A    nexus.pipe(sink)
 .pipe(re
@@ -1214,22 +1214,16 @@
 es);
-%0A    %7D
 %0A%0A    re
 turn
@@ -1222,28 +1222,66 @@
   re
-turn source.pipe(res
+q.on(%22close%22, function() %7B%0A      nexus.unpipe(sink);%0A    %7D
 );%0A 

Unplug client streams when requests end