/*
 * LOGICAL-PARADOX.ORG
 * Copyright (C)2005 satoshi akabane(akabane@logical-paradox.org)
 * $Id: ping.java,v 1.2 2005/09/07 13:38:06 rampil Exp $
 */
package org.logical_paradox.vsan.tools.console.command;

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

import org.logical_paradox.common.util.StringUtils;
import org.logical_paradox.shell.Argument;
import org.logical_paradox.shell.Command;
import org.logical_paradox.shell.ResultCode;
import org.logical_paradox.shell.ShellEnv;
import org.logical_paradox.shell.exception.CommandExecutionException;
import org.logical_paradox.shell.exception.TerminationException;
import org.logical_paradox.vsan.dac.DacConfig;
import org.logical_paradox.vsan.tools.console.DacConsoleConstant;

/**
 * <pre>
 * ■ping
 * 
 * 【動作仕様】
 * DACに対してPINGを打ちます。
 * aliveかnot aliveかが返却されます。
 * このコマンドは、dacコマンドによって設定された'dac'環境変数を参照します。
 * 
 * 【書式】
 * ping [<hostname>[:<port>]]
 * </pre>
 * 
 * @author satoshi akabane@logical-paradox.org
 * @version $Revision: 1.2 $
 */
public class ping implements Command {
	public static final String USAGE = "ping [<hostname>[:<port>]]";

	public String usage() {
		return USAGE;
	}

	public ResultCode execute(OutputStream o, ShellEnv env, Argument a) throws CommandExecutionException, TerminationException {
		String dac = null;

		if(a == null || a.getArguments().length == 0) {
			dac = env.getProperty(DacConsoleConstant.ENV_DAC);
		} else if(a.getArguments().length > 1) {
			throw new CommandExecutionException();
		} else {
			dac = a.getArguments()[0];
		}
		if(a != null && a.getOptions().length > 0 || a != null && a.getArguments().length > 1) {
			throw new CommandExecutionException();
		}

		if(StringUtils.isEmpty(dac) == true) {
			dac = "localhost";
		}

		// ソケットを開くことができるか試行する
		Socket socket = null;
		boolean connection = false;

		if(dac.indexOf(":") == dac.lastIndexOf(":")) {
			String[] tokens = dac.split(":");
			try {
				if(tokens.length == 1) {
					socket = new Socket(tokens[0], DacConfig.DEFAULT_PORT_NUMBER);
				} else {
					socket = new Socket(tokens[0], Integer.parseInt(tokens[1]));
				}
				socket.getOutputStream();
				socket.close();
				
				connection = true;
			} catch(Exception e) {
				// ダメだった
				connection = false;
			}
		} else {
			throw new CommandExecutionException("illegal host format for 'dac'.");
		}

		PrintWriter pw = new PrintWriter(o);
		pw.println("status of '" + dac + "' is : " + (connection == true ? "alive" : "not alive"));
		pw.flush();
		pw.close();

		return new ResultCode(ResultCode.STATUS_OK);
	}

}
