/*
 * $Id: setenv.java,v 1.2 2005/09/07 13:38:06 rampil Exp $
 * Copyright (c) 2004 LOGICAL-PARADOX.ORG
 */
package org.logical_paradox.vsan.tools.console.command;

import java.io.OutputStream;
import java.io.PrintWriter;

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;

/**
 * <pre>
 * ■setenv
 * 
 * 【動作仕様】
 * 環境変数を設定します。
 * 
 * 【書式】
 * setenv <変数名>=<値>
 * </pre>
 * 
 * @author satoshi akabane@logical-paradox.org
 * @version $Revision: 1.2 $
 */
public class setenv implements Command {
	public static final String USAGE = "setenv <variable-name>=<value>";

	/**
	 * 書式を出力する
	 * @param ostream 出力先のストリーム
	 */
	protected void printHelp(OutputStream ostream) {
		PrintWriter pw = new PrintWriter(ostream);
		pw.println("usage: setenv <variable name>=<value>");
		pw.flush();
		pw.close();
	}
	public ResultCode execute(OutputStream arg0, ShellEnv arg1, Argument arg2) throws CommandExecutionException, TerminationException {
		if(
			arg2 == null ||
			arg2.getArguments().length < 1 ||
			arg2.getArguments()[0].indexOf('=') <= 0 ||
			arg2.getArguments()[0].lastIndexOf('=') == arg2.getArguments()[0].length()-1
		) {
			// 引数が足りない場合は書式を出力する
			printHelp(arg0);
			return new ResultCode(ResultCode.STATUS_ERROR);
		}

		// 環境変数を設定する
		StringBuffer argument = new StringBuffer();
		for(int i = 0; i < arg2.getArguments().length; i++) {
			argument.append(" " + arg2.getArguments()[i]);
		}
		String statement = argument.toString().trim();
		int equalPosition = statement.indexOf('=');

		String varname = statement.substring(0, equalPosition);
		String value = statement.substring(equalPosition+1);

		// 環境変数の設定
		arg1.setProperty(varname, value);
		return new ResultCode(ResultCode.STATUS_OK);
	}
	public String usage() {
		return USAGE;
	}
}
