/*jshint node:true */

"use strict";

var accepts = require('accepts'),
    https   = require('https'),
    mime    = require('mime'),
    url     = require('url'),
    zlib    = require('zlib');

var config = require('../../conf');

// Returns a middleware function that proxies a request to the specified
// rootUrl with the current request URL appended, passes through
// appropriate request and response headers, and relays the body of the
// response to the client, ending the request.
module.exports = function (rootUrl) {
    var parsedUrl = url.parse(rootUrl);

    return function (req, res, next) {
        var headers = {};

        config.relayRequestHeaders.forEach(function (header) {
            var value = req.header(header);

            if (value) {
                headers[header] = value;
            }
        });

        // Always request a compressed response from GitHub. We'll decompress it
        // if the client can't handle it.
        headers['accept-encoding'] = 'gzip,deflate';

        var request = https.get({
            hostname: parsedUrl.hostname,
            path    : parsedUrl.path + req.path,
            headers : headers
        });

        request.setTimeout(30000);

        request.on('error', function (err) {
            next(err);
        });

        request.on('response', function (github) {
            var status = github.statusCode;

            if ((status < 200 || status > 299) && status !== 304) {
                // Treat as a 404.
                next();
                return;
            }

            // Pass certain GitHub headers along in the response.
            config.relayResponseHeaders.forEach(function (name) {
                var value = github.headers[name.toLowerCase()];

                if (value) {
                    res.set(name, value);
                }
            });

            var type = mime.lookup(req.path);

            // If GitHub served this file with a specific character encoding, so
            // should we.
            var charset = /;\s*charset\s*=\s*([^\s;]+)/.exec(
                    github.headers['content-type']);

            if (charset) {
                type += '; charset=' + charset[1];
            }

            res.statusCode = status;
            res.type(type);

            var encoding = github.headers['content-encoding'];

            // If GitHub gave us a compressed response and the client can
            // handle it, send GitHub's response directly to the client. If the
            // client can't handle it, then decompress it first.

            // NOTE: For now, we always decompress GitHub responses because
            // passing compressed responses to Nginx seems to lead to spurious
            // 504s (possibly because it's not caching them correctly).

            // if ((encoding === 'gzip' || encoding === 'deflate')
            //         && !accepts(req).encodings(encoding)) {

                github.pipe(zlib.createUnzip()).pipe(res);
            // } else {
            //     res.set('Content-Encoding', encoding);
            //     github.pipe(res);
            // }
        });
    };
};

@@ -1041,16 +1041,45 @@
 s.get(%7B%0A
+            agent   : false,%0A
         
@@ -2598,17 +2598,16 @@
  first.%0A
-%0A
         
@@ -2613,239 +2613,8 @@
     
- // NOTE: For now, we always decompress GitHub responses because%0A            // passing compressed responses to Nginx seems to lead to spurious%0A            // 504s (possibly because it's not caching them correctly).%0A%0A            //
  if 
@@ -2669,27 +2669,24 @@
 %0A           
- //
          && 
@@ -2793,19 +2793,16 @@
         
- //
  %7D else 
@@ -2815,23 +2815,20 @@
         
-//
     
- 
 res.set(
@@ -2869,19 +2869,16 @@
         
- //
      git
@@ -2903,19 +2903,16 @@
         
- //
  %7D%0A     

Disable HTTP connection pooling.