/*
 *  Licensed to GraphHopper and Peter Karich under one or more contributor
 *  license agreements. See the NOTICE file distributed with this work for
 *  additional information regarding copyright ownership.
 *
 *  GraphHopper licenses this file to you under the Apache License,
 *  Version 2.0 (the "License"); you may not use this file except in
 *  compliance with the License. You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.graphhopper.http;

import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.servlet.GuiceFilter;
import com.graphhopper.util.CmdArgs;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletHolder;

import java.util.EnumSet;
import javax.servlet.DispatcherType;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Simple server similar to integration tests setup.
 */
public class GHServer
{
    public static void main( String[] args ) throws Exception
    {
        new GHServer(CmdArgs.read(args)).start();
    }

    private final CmdArgs args;
    private Server server;
    private final Logger logger = LoggerFactory.getLogger(getClass());

    public GHServer( CmdArgs args )
    {
        this.args = args;
    }

    public void start() throws Exception
    {
        Injector injector = Guice.createInjector(createModule());
        start(injector);
    }

    public void start( Injector injector ) throws Exception
    {
        ResourceHandler resHandler = new ResourceHandler();
        resHandler.setDirectoriesListed(false);
        resHandler.setWelcomeFiles(new String[]
        {
            "index.html"
        });
        resHandler.setResourceBase(args.get("jetty.resourcebase", "./src/main/webapp"));

        server = new Server();
        // getSessionHandler and getSecurityHandler should always return null
        ServletContextHandler servHandler = new ServletContextHandler(ServletContextHandler.NO_SECURITY | ServletContextHandler.NO_SESSIONS);
        servHandler.setContextPath("/");        

        servHandler.addServlet(new ServletHolder(new InvalidRequestServlet()), "/*");

        FilterHolder guiceFilter = new FilterHolder(injector.getInstance(GuiceFilter.class));
        servHandler.addFilter(guiceFilter, "/*", EnumSet.allOf(DispatcherType.class));

        int httpPort = args.getInt("jetty.port", 8989);
        SelectChannelConnector connector0 = new SelectChannelConnector();
        // don't allow access from outside!
        // connector0.setHost("127.0.0.1");
        connector0.setPort(httpPort);
        server.addConnector(connector0);

        HandlerList handlers = new HandlerList();
        handlers.setHandlers(new Handler[]
        {
            resHandler, servHandler
        });
        server.setHandler(handlers);
        server.start();
        logger.info("Started server at HTTP " + httpPort);
    }

    private Module createModule()
    {
        return new AbstractModule()
        {
            @Override
            protected void configure()
            {
                binder().requireExplicitBindings();

                install(new DefaultModule(args));
                install(new GHServletModule());

                bind(GuiceFilter.class);
            }
        };
    }

    public void stop()
    {
        try
        {
            server.stop();
        } catch (Exception ex)
        {
            logger.error("Cannot stop jetty", ex);
        }
    }
}

@@ -1060,16 +1060,51 @@
 mdArgs;%0A
+import java.net.InetSocketAddress;%0A
 import o
@@ -2830,24 +2830,16 @@
 th(%22/%22);
-        
 %0A%0A      
@@ -3105,64 +3105,8 @@
 );%0A%0A
-        int httpPort = args.getInt(%22jetty.port%22, 8989);%0A
     
@@ -3187,54 +3187,113 @@
     
-// don't allow access from outside!%0A 
+int httpPort = args.getInt(%22jetty.port%22, 8989);%0A        String host = args.get(%22jetty.host%22, %22%22);%0A
        
-//
  con
@@ -3307,35 +3307,62 @@
 .set
-Host(%22127.0.0.1%22);%0A
+Port(httpPort);%0A        if (!host.isEmpty())%0A 
         
 conn
@@ -3349,32 +3349,35 @@
 pty())%0A         
+   
 connector0.setPo
@@ -3370,39 +3370,44 @@
 nnector0.set
-Port(httpPort);
+Host(host);%0A        
 %0A        ser
@@ -3696,16 +3696,29 @@
 HTTP %22 +
+ host + %22:%22 +
  httpPor

make host to bind configurable