/*
 * Server for the naming service bank example.
 */

#include "Naming/Bank/BankS.h"
#include "Naming/Bank/BankC.h"
#include "Naming/Bank/AccountManagerImpl.h"
#include "Naming/Bank/Util.h"

#include <tao/corba.h>
#include <orbsvcs/Shutdown_Utilities.h>

class Service_Shutdown_Functor : public Shutdown_Functor
{
public:
  Service_Shutdown_Functor (CORBA::ORB_ptr orb)
    : orb_ (CORBA::ORB::_duplicate (orb))
  {
  }

  void operator() (int which_signal)
  {
    ACE_DEBUG ((LM_DEBUG,
                ACE_TEXT ("shutting down on signal %d\n"),
                which_signal));
    (void) this->orb_->shutdown ();
  }

private:
  CORBA::ORB_var orb_;
};

int
main (int argc, char** argv)
{
  try
    {
      // Get the ORB reference.
      CORBA::ORB_var orbVar = CORBA::ORB_init (argc, argv);
      if (CORBA::is_nil (orbVar.in ()))
        {
          ACE_ERROR_RETURN ((LM_ERROR,
                             ACE_TEXT ("ERROR: Could not instantiate the ORB\n")),
                            1);
        }
      Service_Shutdown_Functor killer (orbVar.in ());
      Service_Shutdown kill_contractor (killer);

      // Create the servant.
      Util util (orbVar.in ());
      AccountManagerImpl *pServant = 0;
      ACE_NEW_THROW_EX (pServant,
                        AccountManagerImpl (util),
                        CORBA::NO_MEMORY ());
      PortableServer::ServantBase_var holder (pServant);

      PortableServer::POA_var poaVar = util.getRootPOA ();
      PortableServer::POAManager_var poaManagerVar = poaVar->the_POAManager ();
      poaManagerVar->activate ();

      PortableServer::ObjectId_var oid =
        poaVar->activate_object (pServant);
      CORBA::Object_var servantObjectVar =
        poaVar->servant_to_reference (pServant);

      // Run the server.
      util.buildNameGraph ();
      util.bindAccountManager (servantObjectVar.in ());

      ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Waiting to receive incoming requests\n")));
      orbVar->run ();

      // Complete.
      orbVar->destroy ();
    }
  catch (const CORBA::Exception &ex)
    {
      ex._tao_print_exception (ACE_TEXT ("ERROR: Exception in BankManager.cpp:"));
      return 1;
    }

  return 0;
}
