import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;


/**
 * When this program is run, it tries to shut down a BuddyChatServer running
 * on the same machine and, ordinarily, started by the same user.  It assumes
 * that the server was started on the default port; if not, a different port
 * must be specified on the command line.  (The shutdown string that is needed
 * to shut down the server is in a file that is created when the server is
 * run in the home directory of the user who started the server.  The
 * name of the file is .BuddyChatServer_shutdown_string_port, with "port"
 * replaced by the port number on which the server is listening.)
 */
public class BuddyChatServerShutdown {
   
   private static final int DEFAULT_PORT = 12001;
   private static final String DEFAULT_SHUTDOWN_MESSAGE ="skRl@(Gjfd908.89d&*hgfd";
   
   
   public static void main(String[] args) {
      int port = DEFAULT_PORT;
      if (args.length > 0) {
         try {
             int p = Integer.parseInt(args[0]);
             if (p <= 0 || p > 65535)
                throw new NumberFormatException();
             port = p;
         }
         catch (NumberFormatException e) {
         }
      }
      String shutdownString = DEFAULT_SHUTDOWN_MESSAGE;
      File file = new File(System.getProperty("user.home"), 
            ".BuddyChatServer_shutdown_string_" + port);
      try {
         BufferedReader in = new BufferedReader(new FileReader(file));
         shutdownString  = in.readLine();
      }
      catch (Exception e) {
         shutdownString = DEFAULT_SHUTDOWN_MESSAGE;
      }
      try {
         Socket socket = new Socket("localhost",port);
         BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
         String reply = in.readLine();
         if (! "BuddyChatServer".equals(reply))
            throw new Exception("Didn't receive expected handshake from server.");
         PrintWriter out = new PrintWriter(socket.getOutputStream());
         out.println("BuddyChatClient");
         out.println(shutdownString);
         out.flush();
         reply = in.readLine();
         if (! "shutting down".equals(reply))
            throw new Exception("Didn't receive expected reply from server.");
         socket.close();
      }
      catch (Exception e) {
         System.out.println("Error occurred during shutdown:");
         System.out.println(e);
      }
   }


}
