package com.interpress_project.modernshare.client;

import com.interpress_project.modernshare.AppKeys;
import com.interpress_project.modernshare.client.controller.delegate.exceptions.AccountNotFoundException;

/**
 * @stereotype Main
 */
public class Passwd extends IUserAdmin {
	/**
	 * Useradd
	 * @param args
	 */
	public Passwd(String[] args) {
		super(args);

		sb.setLoggerInfo(AppKeys.ProgramName, AppKeys.LogFilename);
	}

	/**
	 * parseOptions
	 * @param args
	 */
	protected void parseOptions(String[] args) {
		if (args.length == 0) {
			usage();
			System.exit(-1);
		}
		for (int i = 0; i < args.length; i++) {
			if ("-rootpass".equalsIgnoreCase(args[i])) {
				setRootPassword(args[++i]);
			}
			else if ("-user".equalsIgnoreCase(args[i])) {
				setNewAccount(args[++i]);
			}
			else if ("-pass".equalsIgnoreCase(args[i])) {
				setNewPassword(args[++i]);
			}
			else if ("-host".equalsIgnoreCase(args[i])) {
				setAdminHost(args[++i]);
			}
			else if ("-port".equalsIgnoreCase(args[i])) {
				setAdminPort(new Integer(args[++i]).intValue());
			}
		}
		if (getRootPassword().length() == 0 || getNewAccount().length() == 0 || getNewPassword().length() == 0) {
			usage();
			System.exit(-1);
		}
	}

	/**
	 * usage
	 */
	private void usage() {
		System.out
		    .println("Usage: passwd -rootpass <pass> -user <account> -pass <newpass> -host <targethost> -port <portnum>");
		System.out.println("HotShot utility passwd changes login password and password attributes.");
		System.out.println("\t-rootpass <pass>\t: Password for root account.");
		System.out.println("\t-user <account>\t\t: The login ID of target user.");
		System.out.println("\t-pass <newpass>\t: The password newly-assigned for the login ID.");
		System.out.println("\t-host <hostname>\t: The hostname of HotShot datacenter.");
		System.out.println("\t-port <number>\t\t: Port number of HotShot datacenter.");
	}

	/**
	 * run
	 * The ORB/SVN connections carried out in the upper layer.
	 */
	@Override
	protected void run() {
		try {
			orbmgr.changePassword("root", getRootPassword(), getNewAccount(), getNewPassword());
		}
		catch (AccountNotFoundException ex) {
			String msg = ex.getMessage();
			sb.getLogger().error(msg);
			return;
		}
		catch (Exception ex) {
			sb.getLogger().fatal(ex.getMessage());
			return;
		}
		sb.getLogger().info("アカウント" + getNewAccount() + "のパスワード変更に成功しました。");
	}

	/**
	 * main
	 * @param args
	 */
	public static void main(String[] args) {
		IUserAdmin admin = new Passwd(args);
		admin.exec();
	}
}
