/*
 * MyFirstOrbit program - server. Hacked
 * from Echo test suite by birney@sanger.ac.uk
 */

#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "signal.h"
#include "orb/orbit.h"
#include "msg.h"
/* This is so we can get out a valid IOR later... */
CORBA_Object msg_client = CORBA_OBJECT_NIL;

/* declaration of the meat of the process*/
static void
do_submit(PortableServer_Servant servant,
              CORBA_char *astring,
              CORBA_Environment *ev);

PortableServer_ServantBase__epv base_epv = {
  NULL,
  NULL,
  NULL
};
POA_MESSAGING_mail__epv MESSAGING_epv = { NULL, do_submit };
POA_MESSAGING_mail__vepv poa_echo_vepv = { &base_epv, &MESSAGING_epv };
POA_MESSAGING poa_MESSAGING_servant = { NULL, &poa_MESSAGING_vepv };


int
main (int argc, char *argv[])
{
    PortableServer_ObjectId objid = {0, sizeof("myEchoString"), "myEchoString"};
    PortableServer_POA poa;

    CORBA_Environment ev;
    char *retval;
    CORBA_ORB orb;
    FILE * ofp;

    signal(SIGINT, exit);
    signal(SIGTERM, exit);

    CORBA_exception_init(&ev);
    orb = CORBA_ORB_init(&argc, argv, "orbit-local-orb", &ev);

    POA_MESSAGING__init(&poa_MESSAGING_servant, &ev);

    poa = (PortableServer_POA)CORBA_ORB_resolve_initial_references(orb, "RootPOA", &ev);
    PortableServer_POAManager_activate(PortableServer_POA__get_the_POAManager(poa, &ev), &ev);
    PortableServer_POA_activate_object_with_id(poa,
                                               &objid, &poa_MESSAGING_servant, &ev);

    MESSAGING_client = PortableServer_POA_servant_to_reference(poa,
                                                          &poa_MESSAGING_servant,
                                                          &ev);
    if (!MESSAGING_client) {
        printf("Cannot get objref\n");
        return 1;
    }

    retval = CORBA_ORB_object_to_string(orb, MESSAGING_client, &ev);

    ofp = fopen("msg.ior","w");

    fprintf(ofp,"%s", retval);
    fclose(ofp);

    CORBA_free(retval);

    fprintf(stdout,"Written the file msg.ior with the IOR of this server.\n Now waiting for requests...\n");
    fflush(stdout);
    CORBA_ORB_run(orb, &ev);

    return 0;
}

static void
do_echoString(PortableServer_Servant servant,
              CORBA_char *astring,
              CORBA_Environment *ev)
{
  g_message("[server] %s", astring);
  return;
}

