public int doBegin(String[] argv, PrintStream out, InputStream in) {
buildOptions(argv, out, in);
int result = 0;
Server server = null;
try {
CommandLineParser argParser = new GnuParser();
CommandLine commands;
try {
commands = argParser.parse(mergedOptions, argv);
} catch (Throwable t) {
log.error(
"Unexpected error parsing arguments: "
+ Arrays.asList(argv), t);
return 127;
}
LinkedList<String> arguments = new LinkedList<String>();
for (Object o : commands.getArgList()) {
arguments.add(o.toString()); // dodge untyped param warning
}
if (commands.hasOption("?")) {
printAllUsage();
return 0;
}
if (arguments.size() < 1) {
printAllUsage();
return 127; // "command not found"
}
if (!commands.hasOption("strict")) {
// most trsst nodes run with self-signed certificates,
// so by default we accept them
Common.enableAnonymousSSL();
} else {
System.err.println("Requiring signed SSL");
}
// System.out.println("Commands: " + arguments );
String mode = arguments.removeFirst().toString();
// for port requests
if ("serve".equals(mode)) {
// start a server and exit
result = doServe(commands, arguments);
return 0;
}
// attempt to parse next argument as a server url
Client client = null;
if (commands.hasOption("h")) {
String host = commands.getOptionValue("h");
try {
URL url = new URL(host);
// this argument is a server url
client = new Client(url);
System.err.println("Using service: " + host);
} catch (MalformedURLException e) {
// otherwise: ignore and continue
System.err.println("Bad hostname: " + host);
}
}
// if a server url wasn't specified
if (client == null) {
// start a client with a local server
server = new Server();
client = new Client(server.getServiceURL());
System.err.println("Starting temporary service at: "
+ server.getServiceURL());
}
if ("pull".equals(mode)) {
// pull feeds from server
result = doPull(client, commands, arguments, out);
} else if ("push".equals(mode)) {
// push feeds to server
result = doPush(client, commands, arguments, out);
} else if ("post".equals(mode)) {
// post (and push) entries
result = doPost(client, commands, arguments, out, in);
} else {
printAllUsage();
result = 127; // "command not found"
}
} catch (Throwable t) {
log.error("Unexpected error: " + t, t);
result = 1; // "catchall for general errors"
}
if (server != null) {
server.stop();
}
return result;
}