// **********************************************************************
//
// Copyright (c) 1999
// Object Oriented Concepts, Inc.
// Billerica, MA, USA
//
// All Rights Reserved
//
// **********************************************************************

#include <OB/CORBA.h>
#include <OB/Util.h>
#include <OB/CosProperty_impl.h>

#include <Config.h> // Make sure that the compiler complains if the
                    // configuration doesn't match

#include <stdlib.h>

#ifdef HAVE_FSTREAM
#   include <fstream>
#else
#   include <fstream.h>
#endif

static void
usage(const char* progName)
{
    cerr << "Usage:\n";
    cerr << progName << " [options]\n"
	"\n"
	"Options:\n"
	"-h, --help             Show this message.\n"
	"-v, --version          Show Property Service version.\n"
	"-i, --ior              Print IOR on standard output.\n"
	;
}

int
main(int argc, char* argv[], char*[])
{
    try
    {
	//
	// Set program name
	//
	const char* progName = argv[0];
	
	//
	// Create ORB
	//
	CORBA_ORB_var orb = CORBA_ORB_init(argc, argv);
	
	//
	// Resolve the service object if available as an initial reference.
	//
	const char* service = "PropertyService";
	CORBA_Object_var serviceObject;
	try
	{
	    serviceObject = orb -> resolve_initial_references(service);
	}
	catch(CORBA_ORB::InvalidName&)
	{
	}
	
	//
	// Set the IIOP port based on the port defined in the IIOP profile
	// of the service object (if it exists). Then create the BOA.
	//
	CORBA_BOA::set_iiop_port_from_object(serviceObject);
	CORBA_BOA_var boa = orb -> BOA_init(argc, argv);
	
	//
	// Get options
	//
	CORBA_String_var cppArgs;
	bool ior = false;
	
	CORBA_Long i;
	for(i = 1 ; i < argc && *argv[i] == '-' ; i++)
	{
	    if(strcmp(argv[i], "--help") == 0 ||
	       strcmp(argv[i], "-h") == 0)
	    {
		usage(progName);
		return 0;
	    }
	    else if(strcmp(argv[i], "--version") == 0 ||
		    strcmp(argv[i], "-v") == 0)
	    {
		cerr << "Property Service " << OBVersion << endl;
		return 0;
	    }
	    else if(strcmp(argv[i], "--ior") == 0 ||
		    strcmp(argv[i], "-i") == 0)
	    {
		ior = true;
	    }
	    else
	    {
		cerr << progName << ": unknown option `"
		     << argv[i] << "'\n" << endl;
		usage(progName);
		return 1;
	    }
	}
	
	//
	// Create factory
	//
	CosPropertyService_PropertySetDefFactory_var p =
	    new CosPropertyService_PropertySetDefFactory_impl(orb);
	orb -> connect(p, "DefaultPropertySetDefFactory");
	
	//
	// Print IOR on standard output
	//
	if(ior)
	{
	    CORBA_String_var s = orb -> object_to_string(p);
	    cout << s << endl;
	}
	
	//
	// Run implementation
	//
	boa -> impl_is_ready(CORBA_ImplementationDef::_nil());
    }
    catch(CORBA_SystemException& ex)
    {
	OBPrintException(ex);
	return 1;
    }

    return 0;
}
