package winrock;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ShutdownHook extends Thread {
  private final static Logger log = LoggerFactory.getLogger(ShutdownHook.class);
  private Launcher launcher;

  public ShutdownHook(Launcher launcher) {
    this.launcher = launcher;
  }

  public void run() {
    if (this.launcher != null) {
      log.info("ShutdownHook.Initiating");
      this.launcher.shutdown();
    }
  }

  public static void shutdown(int port) throws Exception {
    String serverAddress = "127.0.0.1";
    int serverPortNum = port;
    Socket socket = null;
    String magicWord = "SHUTDOWN";
    byte[] buffer = null;
    OutputStream os = null;
    try {
      /*
       * Change to InetAddress.getHostByName(somehostname) if client is
       * running from a remote machine
       */
      socket = new Socket(serverAddress, serverPortNum);
      os = socket.getOutputStream();
      buffer = magicWord.getBytes();
      os.write(buffer, 0, buffer.length);
      os.flush();

    } finally {
      if (os != null) {
        try {
          os.close();
        } catch (IOException e) {
        }
        os = null;
      }
    }
  }
}
