/**
 * Base URL utilities for the Ajax.org Cloud IDE
 * 
 * Access via require("c9/urls").
 *
 * @copyright 2015, Ajax.org B.V.
 */

var plugin = module.exports = main;
var assert = require("assert");
 
plugin.consumes = ["error.logger"];
plugin.provides = ["urls"];

var errorLogger = mockErrorLogger;

function main(options, imports, register) {
    errorLogger = imports["error.logger"];
    
    register(null, {
        urls: plugin
    });
}

/**
 * Get a desired base URL, given some context.
 * 
 * @param req                             The current request object or URL
 * @param {String} sourceUrlPattern       The source URL pattern, e.g. https://ide.$DOMAIN
 * @param {String} [targetBaseUrlPattern] The target URL pattern, e.g. https://$DOMAIN
 */
plugin.getBaseUrl = function(req, sourceBaseUrlPattern, targetBaseUrlPattern) {
    var sourceHost = req.host || req;
    var sourceHostMatcher = sourceBaseUrlPattern
        .replace(/^https?:\/\//, "")
        .replace(/\/.*/, "")
        .replace("$DOMAIN", "([^/]+)");
    var hostMatch = sourceHost.match(sourceHostMatcher);
    if (!hostMatch) {
        errorLogger.log(new Error("Could not construct URL: request host "
            + sourceHost + " should match " + sourceBaseUrlPattern));
        return replaceDomain(targetBaseUrlPattern || sourceBaseUrlPattern, "c9.io");
    }
    
    return replaceDomain(targetBaseUrlPattern || sourceBaseUrlPattern, hostMatch[1]);
};

plugin.replaceDomains = function(settings, domains) {
    domains = Array.isArray(domains) ? domains : domains.split(",");
    var primaryDomain = domains[0];
    settings.domains = domains;
    settings.primaryDomain = replaceDomain(settings.primaryDomain || "$DOMAIN", primaryDomain);
    settings.primaryBaseUrl = replaceDomain(settings.primaryBaseUrl || "https://$DOMAIN", primaryDomain);
    for (var s in settings) {
        if (!settings[s])
            continue;
        if (settings[s].baseUrl)
            settings[s].baseUrl = replaceDomain(settings[s].baseUrl, primaryDomain);
        if (settings[s].primaryBaseUrl)
            settings[s].primaryBaseUrl = replaceDomain(settings[s].primaryBaseUrl, primaryDomain);
        if (settings[s].baseUrls) {
            assert(settings[s].baseUrls.length === 1);
            settings[s].baseUrls = domains.map(function(d) {
                return replaceDomain(settings[s].baseUrls[0], d);
            });
        }
    }
};

function replaceDomain(url, domain) {
    return url.replace("$DOMAIN", domain);
}

function mockErrorLogger() {}
mockErrorLogger.log = function(err) {
    console.error(err.stack);
};
plugin.mockErrorLogger = mockErrorLogger;

@@ -855,16 +855,51 @@
 ceHost =
+ req.headers && req.headers.host %7C%7C
  req.hos
@@ -1370,16 +1370,48 @@
 %22c9.io%22)
+%0A            .replace(/%5C/$/, %22%22)
 ;%0A    %7D%0A
@@ -1499,16 +1499,45 @@
 atch%5B1%5D)
+%0A        .replace(/%5C/$/, %22%22);
 ;%0A%7D;%0A%0Apl

Make profile multi-domain aware