import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

/*
 * Main class to shutdown the remote server
 */
public class ShutdownServer {	
	private DataInputStream input=null;
	private BufferedOutputStream output=null;
	public ShutdownServer(){		
	}


	public static void main(String arg[]){



		//  open up standard input
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		String userName = null;
		String password = null;
		String server_address = null;

		

		System.out.print("Enter the server address: ");
		try {
			server_address = br.readLine();
		} catch (IOException ioe) {
			System.out.println("IO error trying to read your username!");
			System.exit(1);
		}
		System.out.print("Enter the admin username: ");
		try {
			userName = br.readLine();
		} catch (IOException ioe) {
			System.out.println("IO error trying to read your username!");
			System.exit(1);
		}
		System.out.print("Enter the admin password: ");
		try {
			password = br.readLine();
		} catch (IOException ioe) {
			System.out.println("IO error trying to read your password!");
			System.exit(1);
		}
		ShutdownServer ss= new ShutdownServer();
		ss.shutdown(server_address, 8082, userName, password);
	}

	//	Send shutdown request to the server
	public void shutdown(String ip, int port, String username, String password){
		try {
			Socket socket = new Socket(ip, port);
			input=new DataInputStream(socket.getInputStream());
			output = new BufferedOutputStream( socket.getOutputStream() );
			byte [] output_string = ("Server shutdown request:"+username+":"+password+"/").getBytes();
			for(int i=0;i<output_string.length;i++)
				output.write(output_string[i]);
			output.flush();
			String result = input.readUTF();
			System.out.println(result);
			input.close();
			socket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("Server cannot be shut down");
		}
	}
}
