#!/usr/bin/env node
'use strict';

var restify = require('restify');
var extend  = require('deep-extend');
var q       = require('q');
var fs      = require('fs');
var path    = require('path');
var mkdirp  = require('mkdirp');
var md5     = require('md5');
var wkBinPath = require('wkhtmltopdf-installer').path;
//var app = require('../lib');
var pdfFac  = require('../lib');

var pkg = require('../package.json');

// Get untrackable configurations.
try {
  extend(process.env, require('../config.json')); //eslint-disable-line global-require
} catch (err) {
  if (!err.message || err.code !== 'MODULE_NOT_FOUND') {
    throw err;
  }
}

var writeFile   = q.nfbind(fs.writeFile);
var tmpDir      = process.env.TMP_DIR || path.join(__dirname, '..', '.tmp');
var serviceName = process.env.NAME || pkg.name;
var toPdf       = pdfFac({
  command: process.env.CMD_PATH || wkBinPath || 'wkhtmltopdf'
});

var server = restify.createServer({
  name:    serviceName,
  version: '1.0.0'
});


server.use(
  function crossOrigin (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    return next();
  }
);

server.use(restify.queryParser());
server.use(restify.gzipResponse());

server.post('/', restify.bodyParser(), function (req, res, next) {
  var html   = req.body && req.body.html;
  var header = req.body && req.body.header;
  var footer = req.footer && req.body.footer;

  if (html) {
    Object.getOwnPropertyNames(req.query).forEach(i => {
      let t = req.query[i].toLowerCase();
      if (t === 'true' || t === 'false') {
        req.query[i] = t === 'true';
      }
    });

    var hfProms = [];
    var time    = Date.now();
    if (header) {
      var headerPath = path.join(tmpDir, md5(header) + '-' + time + '.html');
      hfProms.push(writeFile(headerPath, header).then(function () {
        return headerPath
      }));
      req.query['headerHtml'] = headerPath;
    }
    if (footer) {
      var footerPath = path.join(tmpDir, md5(footer) + '-' + time + '.html');
      hfProms.push(writeFile(footerPath, footer).then(function () {
        return headerPath
      }));
      req.query['footerHtml'] = footerPath;
    }

    q.all(hfProms)
      .done(function (paths) {
        toPdf(html, req.query, (err, out) => {
          if (err) {
            next(err);
          } else {

            res.setHeader('content-type', 'application/pdf');
            res.send(out);
            paths.forEach(function (p) {
              fs.unlink(p);
            });
          }
        });
      })
    ;

  } else {
    next(new Error('No HTML body given.'));
  }
});

mkdirp(tmpDir, function (err) {
  if (err) {
    console.log('Server not started, failed to make temporary directory'); //eslint-disable-line no-console
    throw err;
  }

  server.listen(process.env.PORT || 15000, function () {
    console.log('%s server started at %s', server.name, server.url); //eslint-disable-line no-console
  });

});

@@ -40,16 +40,18 @@
 restify 
+  
 = requir
@@ -76,16 +76,18 @@
 extend  
+ 
+ 
 = requir
@@ -112,24 +112,26 @@
 var q       
+  
 = require('q
@@ -142,24 +142,26 @@
 var fs      
+  
 = require('f
@@ -173,24 +173,26 @@
 var path    
+  
 = require('p
@@ -210,16 +210,18 @@
 mkdirp  
+  
 = requir
@@ -241,24 +241,26 @@
 var md5     
+  
 = require('m
@@ -274,20 +274,16 @@
 ar wkBin
-Path
  = requi
@@ -313,24 +313,23 @@
 er')
-.path;%0A//var app
+;%0Avar pdfFac   
  = r
@@ -350,40 +350,163 @@
 ');%0A
+%0A
 var 
-pdfFac  = require('../lib');
+ebTestReg = /%5E%5C/tmp%5C/deployment%5C/application%5C//;%0Aif (ebTestReg.test(wkBin.path)) %7B // in EB%0A  wkBin.path = wkBin.path.replace(ebTestReg, __dirname);%0A%7D
 %0A%0Ava
@@ -999,17 +999,18 @@
 %7C%7C wkBin
-P
+.p
 ath %7C%7C '

fix wkBinPath