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

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

#include <stdlib.h>
#include <stdio.h>

static void
usage(const char* progName)
{
    cerr << "Usage:\n";
    cerr << progName << " [options] scoped-name ...\n"
	"\n"
	"Options:\n"
	"-h, --help             Show this message.\n"
	"-v, --version          Show ORBacus version.\n"
	;
}

int
run(int argc, char* argv[])
{
    //
    // Create ORB
    //
    CORBA_ORB_var orb = CORBA_ORB_init(argc, argv);

    //
    // Set program name
    //
    const char* progName = argv[0];

    //
    // Get options
    //
    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 << "ORBacus " << OBVersion << endl;
	    return 0;
	}
	else
	{
	    cerr << progName << ": unknown option `"
		 << argv[i] << "'\n" << endl;
	    usage(progName);
	    return 1;
	}
    }

    CORBA_Object_var obj;
    try
    {
        obj = orb -> resolve_initial_references("InterfaceRepository");
    }
    catch(CORBA_ORB::InvalidName&)
    {
    }
    if(CORBA_is_nil(obj))
    {
	cerr << "No `InterfaceRepository' initial reference." << endl;
	return 1;
    }

    CORBA_Repository_var repository = CORBA_Repository::_narrow(obj);
    if(CORBA_is_nil(repository))
    {
	cerr << "`InterfaceRepository' initial reference is not a repository."
             << endl;
	return 1;
    }
    
    if(i == argc)
    {
	cerr << progName << ": no scoped name" << endl;
	usage(progName);
	return 1;
    }

    for( ; i < argc ; i++)
    {
	const char* scopedName = argv[i];

	CORBA_Contained_var contained = repository -> lookup(scopedName);

	if(CORBA_is_nil(contained))
	{
	    cerr << progName << ": warning: `" << scopedName
		 << "' does not exist" << endl;
	}
	else
	{
	    contained -> destroy();
	}
    }

    return 0;
}

int
main(int argc, char* argv[], char*[])
{
    int status;

    try
    {
	//
	// Generate code
	//
	status = run(argc, argv);
    }
    catch(CORBA_SystemException& ex)
    {
	OBPrintException(ex);
	status = 1;
    }

    return status;
}
