/*
 * Copyright 2011 the original author or authors.
 *
 * Licensed 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 org.gradle.launcher.daemon.server.exec;

import org.gradle.api.logging.Logger;
import org.gradle.api.logging.Logging;

import org.gradle.messaging.remote.internal.DisconnectAwareConnection;

public class WatchForDisconnection implements DaemonCommandAction {

    private static final Logger LOGGER = Logging.getLogger(WatchForDisconnection.class);

    public void execute(final DaemonCommandExecution execution) {
        DisconnectAwareConnection connection = execution.getConnection();

        // Watch for the client disconnecting before we call stop()
        connection.onDisconnect(new Runnable() {
            public void run() {
                LOGGER.warn("client disconnection detected, we're going down (hard)");
                execution.getDaemonStateCoordinator().stop(); // to remove us from the registry
                System.exit(1);
            }
        });

        execution.proceed();

        // TODO - Do we need to remove the disconnect handler here?
        // I think we should because if the client disconnects after we run the build we may as well stay up
        connection.onDisconnect(null);
    }

}
@@ -1321,112 +1321,453 @@
 ed, 
-we're going down (hard)%22);%0A                execution.getDaemonStateCoordinator().stop(); // to remove us
+stopping the daemon%22);%0A                %0A                /*%0A                    When the daemon was started through the DaemonMain entry point, this will cause the entire%0A                    JVM to exit with code 1 (which is what we want) because the call to awaitIdleTimeout() in %0A                    DaemonMain#doAction will throw a DaemonStoppedException. Note that at this point we will also %0A                    immediately remove the daemon
  fro
@@ -1780,17 +1780,20 @@
 registry
-%0A
+.%0A  
         
@@ -1802,23 +1802,77 @@
     
-  System.exit(1
+*/%0A                execution.getDaemonStateCoordinator().requestStop(
 );%0A 

remove the explicit System.exit(1) call when the daemon detects a client disconnection, relying on the DaemonMain entry point to respond to the daemon stopping and tear down the JVM.