package com.greenautomation.pkeytool;
import java.util.*;
public final class pkeytool {
private final Map COMMAND_MAP = new LinkedHashMap();
private final Set PARAMS_WITHARGS_SET = new HashSet();
private final Set PARAMS_NOARGS_SET = new HashSet();
private final String[] ARGS;
public static void main(String[] args) {
try {
new pkeytool(args).run();
}
catch (PKeyToolException ex) {
System.err.println(ex.getMessage());
}
catch (Exception ex) {
System.err.println("pkeytool error: " + ex);
ex.printStackTrace();
}
}
public pkeytool(String[] args) {
this.ARGS = args;
addCommand(new ExportKeyCommand());
addCommand(new ImportKeyCommand());
addCommand(new ListCommand());
}
public void addCommand(Command command) {
COMMAND_MAP.put(command.getName(), command);
PARAMS_WITHARGS_SET.addAll(Arrays.asList(command.getParamsWithArgs()));
PARAMS_NOARGS_SET.addAll(Arrays.asList(command.getParamsWithoutArgs()));
}
public void run() throws Exception {
Map map = new HashMap();
Command command = null;
for (int i = 0; i < ARGS.length; i++) {
Command cmd = (Command) COMMAND_MAP.get(ARGS[i]);
if (cmd != null) {
command = cmd;
}
else if (PARAMS_WITHARGS_SET.contains(ARGS[i])) {
if (i + 1 >= ARGS.length) {
throw new PKeyToolException(
"Option requires an argument: " + ARGS[i]);
}
map.put(ARGS[i], ARGS[++i]);
}
else if (PARAMS_NOARGS_SET.contains(ARGS[i])) {
map.put(ARGS[i], "");
}
else {
throw new PKeyToolException("Illegal option: " + ARGS[i]);
}
}
if (command == null) {
usage();
return;
}
command.run(map);
}
private final void usage() {
System.err.println("pkeytool usage:");
System.err.println();
Iterator iter = COMMAND_MAP.values().iterator();
while (iter.hasNext()) {
Command command = (Command) iter.next();
command.printHelp(System.err);
System.err.println();
}
}
}