/*
* JBoss, Home of Professional Open Source
* Copyright 2005, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/

package org.jboss.cache.interop;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * Opens a connection to the socket created by {@link Main} and
 * tells it to shut down.
 * 
 * @author Brian Stansberry
 * @version $Revision$
 */
public class Shutdown
{
   private static final Log log = LogFactory.getLog(Shutdown.class);
   
   private int listenerPort_ = 11111;
   private String bindAddressString_;

   /**
    * Create a new Shutdown.
    * 
    */
   public Shutdown()
   {
      super();
   }

   public void shutdown(final String[] args) throws Exception
   {
      // First process the command line to pickup custom props/settings
      processCommandLine(args);
      
      Socket sock = new Socket(bindAddressString_, listenerPort_);
      
      OutputStream ostream = sock.getOutputStream();
      ObjectOutputStream oos = new ObjectOutputStream(ostream);
      InputStream istream = sock.getInputStream();
      ObjectInputStream ois = new ObjectInputStream(istream);
      
      oos.writeObject("SHUTDOWN");
      
      String rsp = (String) ois.readObject();
      
      if (!("OK".equals(rsp)))
         throw new Exception("Shutdown failed -- response from Main is " + rsp);
   }
   
   /**
    * 
    * @param args
    */
   public static void main(String[] args)
   {
      Shutdown s = new Shutdown();
      try
      {
         s.shutdown(args);
      }
      catch (Exception e)
      {
         log.error(e);
      }

   }
   
   private void processCommandLine(final String[] args)
   {
      if (args == null || args.length == 0 || args[0] == null)
      {
         return;
      }
      
      listenerPort_ = Integer.parseInt(args[0]);
      
      if (args.length > 1)
      {
         bindAddressString_ = args[1];
      }
   }

}
