package relational;

import COM.claymoresystems.ptls.*;
import proof.*;
import sdsi.*;
import ssh.*;
import Tools.*;

import java.io.*;
import java.net.*;
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;

/**
 * Creates a remotely-accessible Database that is accessed using
 * Snowflake-authorized RMI-over-SSH.
 */
public class SSHDatabase {
	/**
	 * Unix command-line interface.
	 */
	public static void main(String[] args) {
		try {
			if (System.getSecurityManager()==null) {
				System.setSecurityManager(new RMISecurityManager());
			}

			Options opts = new Options(args) {
				public void defineOptions() {
					programName = "SSHDatabase";
					defineArgument(
		"publicKey", true, "The public key that owns this database "
		+"(an s-expression or filename; hash OK)", "certs-server/serverkey");
				}
			};

			String serverKeyLoc = opts.get("publicKey");
			SDSIPrincipal serverPublicKey;
			Hash serverPublicHash;

			if (serverKeyLoc.charAt(0)=='(') {
				// this is an s-expression. Parse it.
				serverPublicKey =
					(SDSIPrincipal) KeyTools.parseString(serverKeyLoc);
			} else {
				serverPublicKey =
					(SDSIPrincipal) KeyTools.processFilename(serverKeyLoc);
			}
			if (serverPublicKey instanceof Hash) {
				serverPublicHash = (Hash) serverPublicKey;
			} else {
				serverPublicHash = new Hash("md5", serverPublicKey);
			}

			// TODO: should factor out some standard way of seeding
			// this context thing.
			SSHContext context = SSHContext.getDefault();

			Database theDatabase =
				new InternalDatabase(context, serverPublicKey);
			InetAddress thisHost = InetAddress.getLocalHost();
			Naming.rebind("//"+thisHost.getHostName()+"/RMIDatabase",
				theDatabase);
			System.out.println("Database registered in RMI");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}
