package com.ociweb.JavaServer;

//run as: java -jar JavaServer.jar
//orbd -ORBInitialPort 1050

import java.lang.management.ManagementFactory;
import org.apache.commons.cli.*;

import com.ociweb.JavaAddLib.*;

public class JavaServer {
	public static CommandLine ParseArgs(String[] args) {
		try {
			// http://commons.apache.org/cli/usage.html
			CommandLineParser parser = new PosixParser();
			Options options = new Options();
			options.addOption("?", "help", false, "print this message");
			options.addOption(null, "ORBInitialPort", true, "nameserver port (required)");
			options.addOption(null, "ORBInitialHost", true, "nameserver host");
			CommandLine line = parser.parse( options, args );
			
			if (line.hasOption("help") || !line.hasOption("ORBInitialPort")) {
				HelpFormatter formatter = new HelpFormatter();
				formatter.printHelp("Server", options);
				return null;
			}
			
			return line;
		} catch (ParseException e) {
			System.out.println(e.getMessage());
			return null;
		}
	}

	public static void main(String[] args) {
		try {
			CommandLine line = ParseArgs(args);
			if (line == null)
				return;
			
			// http://stackoverflow.com/questions/35842/how-can-a-java-program-get-its-own-process-id
			String instanceName = "Java_" + ManagementFactory.getRuntimeMXBean().getName();
			final AddServer s = new AddServer();
			
		    Runtime.getRuntime().addShutdownHook(new Thread() {
		        public void run() {
		          System.out.println("Shutting down...");
		          s.shutdown();
		        }
		      });
			
		    s.init(args);
			System.out.println("Running " + instanceName);
			s.run(instanceName); 
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
