var express = require('express'),
    parseUrl = require('parseurl'),
    path = require('path'),
    http = require('http'),
    https = require('https'),
    url = require('url'),
    tamper = require('tamper'),
    serverbase = require('./serverbase.js'),
    config = require('./config'),
    httpProxy = require('http-proxy'),
    app = module.exports = express(),
    proxy = new httpProxy.createProxyServer({});

proxy.on('error', function() {
});

function rewriteRules(req, res, next) {
  var u = parseUrl(req);
  if (u.pathname == '/') { u.pathname = '/welcome.html'; }
  else if (/^\/edit\//.test(u.pathname)) {
    if (/^frame\./.test(req.headers['host'])) {
      u.pathname = '/framed.html';
    } else {
      u.pathname = '/editor.html';
    }
  }
  else if (/^\/home(?=\/).*\/$/.test(u.pathname)) { u.pathname = '/dir.html'; }
  else { next(); return; }
  req.url = url.format(u);
  next();
}

var expandSiteInclude = tamper(function(req, res) {
  if (!/^(?:(?:https?:)?\/\/[^\/]+)?\/[^\/]*\.html$/i.test(req.url)) {
    return;
  }
  return function(body) {
    if (res.locals.site) {
      body = body.replace(/<!--#echo var="site"-->/g,
          res.locals.site + res.locals.portpart);
    }
    if (res.locals.filepath) {
      body = body.replace(/<!--#echo var="filepath"-->/g, res.locals.filepath);
    }
    return body;
  }
});

function noAppcache(req, res, next) {
  var u = parseUrl(req);
  if (/\.appcache$/.test(u.pathname)) {
    res.status(404).send()
  } else {
    next();
  }
}

function proxyRules(req, res, next) {
  var u = parseUrl(req);
  var exp = (req.app.locals.config.useProxy) ?
    /^\/(?:code|home|load|save|proxy|img|link|print|socket\.io)(?=\/)/
       : /^\/(?:proxy)(?=\/)/;
  if (exp.test(u.pathname) &&
      /\.dev$/.test(u.host)) {
    var host = req.headers['host'] = u.host.replace(/\.dev$/, '');
    req.headers['url'] = u.path;
    proxy.web(req, res, {
      target: { host: host, port: 80 },
      xfwd: true
    });
  } else {
    next();
  }
}

function proxyPacGenerator(req, res, next) {
  var u = parseUrl(req);
  if (u.pathname == '/proxy.pac') {
    var hostHeader = req.get('host'),
        hostMatch = /^([^:]+)(?::(\d*))?$/.exec(hostHeader || ''),
        hostDomain = (hostMatch && hostMatch[1]) || 'localhost',
        hostPort = (hostMatch && hostMatch[2]) || process.env.PORT;
    res.writeHead(200, {
        'Content-Type': 'text/plain'
    });
    res.end(
        'function FindProxyForURL(url, host) {\n' +
        ' if (shExpMatch(host, "*.dev") || ' +
              'host == "drive.pencilcode.net") {\n' +
        '  return "PROXY ' + hostDomain + ':' + hostPort + '";\n' +
        ' }\n' +
        ' return "DIRECT";\n' +
        '}\n'
    );
  } else {
    next();
  }
}


serverbase.initialize(app);
app.use(rewriteRules);
app.use(expandSiteInclude);
app.use(noAppcache);
app.use(proxyRules);
app.use(proxyPacGenerator);
serverbase.initialize2(app);

var server = false;
if (app.locals.config.useHttps) {
  var fs = require('fs')
  var options = {
    key: fs.readFileSync('server/devserver-key.pem'),
    cert: fs.readFileSync('server/devserver-cert.pem')
  };
  server = https.createServer(options, app);
} else {
  server = http.createServer(app);
}
server.listen(process.env.PORT, function() {
  console.log('Express server listening on ' + process.env.PORT);
});

@@ -516,34 +516,32 @@
 req);%0A  if (
-u
+req
 .path
-name
  == '/') %7B u
@@ -538,16 +538,20 @@
 = '/') %7B
+%0A   
  u.pathn
@@ -568,28 +568,28 @@
 lcome.html';
- %7D
 %0A 
+ %7D
  else if (/%5E
@@ -599,34 +599,32 @@
 dit%5C//.test(
-u
+req
 .path
-name
 )) %7B%0A    if 
@@ -651,24 +651,21 @@
 .headers
-%5B'
+.
 host
-'%5D
 )) %7B%0A   
@@ -753,18 +753,16 @@
    %7D%0A  %7D
-%0A 
  else if
@@ -789,30 +789,32 @@
 $/.test(
-u
+req
 .path
-name
 )) %7B
+%0A   
  u.pathn
@@ -835,27 +835,31 @@
 ml';
- %7D
 %0A 
+ %7D
  else %7B
+%0A   
  next();
  ret
@@ -854,24 +854,28 @@
  next();
+%0A   
  return;
  %7D%0A  req
@@ -866,16 +866,18 @@
  return;
+%0A 
  %7D%0A  req
@@ -1398,33 +1398,8 @@
 ) %7B%0A
-  var u = parseUrl(req);%0A
   if
@@ -1419,26 +1419,24 @@
 $/.test(
-u
+req
 .path
-name
 )) %7B%0A   
@@ -1531,33 +1531,8 @@
 ) %7B%0A
-  var u = parseUrl(req);%0A
   va
@@ -1695,28 +1695,20 @@
 est(
-u
+req
 .path
-name) &&%0A     
+) &&
  /%5C.
@@ -1718,22 +1718,28 @@
 $/.test(
-u
+req
 .host
+name
 )) %7B%0A   
@@ -1776,14 +1776,20 @@
 %5D = 
-u
+req
 .host
+name
 .rep
@@ -1833,17 +1833,19 @@
 url'%5D = 
-u
+req
 .path;%0A 
@@ -2015,47 +2015,20 @@
 %7B%0A  
-var u = parseUrl(req);%0A  if (u
+if (req
 .path
-name
  == 

Fix devserver proxying.