/*-----------------------------------------------------------------*/
/*! 
  \file scscpservertestxx.cpp
  \brief default C++ server tests
  \author  M. Gastineau 
           Astronomie et Systemes Dynamiques, IMCCE, CNRS, Observatoire de Paris. 

   Copyright, 2008, 2009, 2010, 2011, 2012, M. Gastineau, IMCCE-CNRS
   email of the author : gastineau@imcce.fr

  \bug M. GASTINEAU 20/04/09 : update for SCSCP 1.3
  \bug M. GASTINEAU 27/08/09 : test for ticket [#6399] openmath encoded with namespaces are rejected
  \bug M. GASTINEAU 01/10/12 : ticket [#8521] tests hangs or are too long
*/
/*-----------------------------------------------------------------*/

/*-----------------------------------------------------------------*/
/* License  of this file :
 This file is "dual-licensed", you have to choose one  of the two licenses 
 below to apply on this file.
 
    CeCILL-C
    	The CeCILL-C license is close to the GNU LGPL.
    	( http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.html )
 
 or CeCILL v2.0
      The CeCILL license is compatible with the GNU GPL.
      ( http://www.cecill.info/licences/Licence_CeCILL_V2-en.html )
 

This library is governed by the CeCILL-C or the CeCILL license under 
French law and abiding by the rules of distribution of free software.  
You can  use, modify and/ or redistribute the software under the terms 
of the CeCILL-C or CeCILL license as circulated by CEA, CNRS and INRIA  
at the following URL "http://www.cecill.info". 

As a counterpart to the access to the source code and  rights to copy,
modify and redistribute granted by the license, users are provided only
with a limited warranty  and the software's author,  the holder of the
economic rights,  and the successive licensors  have only  limited
liability. 

In this respect, the user's attention is drawn to the risks associated
with loading,  using,  modifying and/or developing or reproducing the
software by the user in light of its specific status of free software,
that may mean  that it is complicated to manipulate,  and  that  also
therefore means  that it is reserved for developers  and  experienced
professionals having in-depth computer knowledge. Users are therefore
encouraged to load and test the software's suitability as regards their
requirements in conditions enabling the security of their systems and/or 
data to be ensured and,  more generally, to use and operate it in the 
same conditions as regards security. 

The fact that you are presently reading this means that you have had
knowledge of the CeCILL-C or CeCILL license and that you accept its terms.
*/
/*-----------------------------------------------------------------*/

#if HAVE_CONFIG_H
#include "scscpconfig.h"
#endif /*HAVE_CONFIG_H*/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <signal.h>
#if HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#if HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#define __SCSCP_WITHIN_SCSCP
#include "scscpxx.h"
#include "scscpsscommon.h"
#include "scscpdebug.h"
#include "scscpfileserver.h"

using namespace SCSCP;
using namespace std;

#if defined(SIGUSR2)
#define SIGNALINTERRUPT SIGUSR2
#else
#define SIGNALINTERRUPT SIGINT
#endif

/*! SCSCP server  */
static Server *server;
static int closesig=0; /* =1 si signal recu */

static int  processcall(IncomingClient *incomingclient,  int typeanswer);
static int server_sendreplycheck(IncomingClient::Computation& task, const char *value, const char *valueref);
static int server_sendreplycheckint(IncomingClient::Computation& task, int value, int valueref);
static int server_sendreplycheckdouble(IncomingClient::Computation& task,  double value, double valueref);


/*-----------------------------------------------------------------*/
/*! stop the server when it receive SIGUSR2  */
/*-----------------------------------------------------------------*/
static void stopserver(int sig)
{

 SCSCP_debugprint("server receive SIGUSR2\n"); 
 closesig=1;
 /* close the connection */
 server->close();

}

/*-----------------------------------------------------------------*/
/*! start the server and listen on default port */
/*-----------------------------------------------------------------*/
static int runserver(int typeanswer, int fd)
{
 int res=0;
 IncomingClient *incomingclient;
 int port = SCSCP_PROTOCOL_DEFAULTPORT;
 
 /*printf("server thread started\n");*/
 /* register stopserver for the signal SIGUSR2 */
 signal(SIGNALINTERRUPT, stopserver);
 
 /*initialization of the server */
 try
 {
  server = new Server("MYCAS","1","myid"); 
               
  if (fd==-1)
  {
     port = SCSCP_PROTOCOL_DEFAULTPORT;
     res = server->listen(port); 
  }
  else
  {
     socklen_t lenadresseServeur=sizeof(struct sockaddr_in);
     struct sockaddr_in adresseServeur;
     /* choose a random port */
     port = 0;
     res = server->listen(port); 
     if (res) 
     {
      memset(&adresseServeur, 0, sizeof(adresseServeur));
      if (getsockname(SCSCP_serverxx_getsocket(*server), (struct sockaddr *)&adresseServeur, 
                      &lenadresseServeur)!=0) 
      {
       printf("getsockname fails\n");
       res = 0;
      }
      port = ntohs(adresseServeur.sin_port);
     }
     /* write the port used by the server to the client */
     if (res)
     {
      SCSCP_debugprint("fd=%d -> port:%d\n", fd, port);
      write(fd,&port, sizeof(port));
     }
     close(fd);   
  }
 

 if (res)
 {
      while ((incomingclient=server->acceptclient())!=NULL)
      {
      SCSCP_debugprint("new client accepted !\n");
       try
       {
        while (res>0) res = processcall(incomingclient,typeanswer);
       }
       catch (Exception e)
       {
        /*cout <<"SCSCP::Exception1 "<<e.what()<<endl;*/
        if (incomingclient->eof()) res = 1; /*-1;*/
       }
       delete incomingclient;
       incomingclient = NULL;
      }
 }
 if (res==0) printf("error \n");
 }
 catch (Exception e)
 {
  if (closesig==0) cout <<"SCSCP::Exception "<<e.what()<<endl;
 }
 SCSCP_debugprint("server exit %d typeanswer=%d\n", closesig, typeanswer); 
 if (res!=-1 && closesig==0) printf("destroy server\n");
 /* destroy the server */
 server->close();
 delete server;
 if (res!=-1  && closesig==0) 
 {
  printf("server thread crash => exit with value 1\n");
  printf("----------------------------------------\n");
  printf(" reports this bug to %s \n", PACKAGE_BUGREPORT);
  printf("----------------------------------------\n");
  return 1; 
 }
 else
 {
  return 0;
 }
}


/*-----------------------------------------------------------------*/
/*! send the answer : if value==valueref then 
 send a completed message  */
/*-----------------------------------------------------------------*/
static int server_sendreplycheck(IncomingClient::Computation& task,  const char *value, const char *valueref)
{
 int res;
 if (strcmp(value,valueref)!=0)
 {
   task.sendterminated("scscp1", "error_system_specific", value!=NULL?value:"null");
   res = 0;
 }
 else
 {
    res = task.sendcompleted("<OMI>1</OMI>"); 
 }
 return res;
}

/*-----------------------------------------------------------------*/
/*! send the answer : if value==valueref then 
 send a completed message  */
/*-----------------------------------------------------------------*/
static int server_sendreplycheckint(IncomingClient::Computation& task, int value, int valueref)
{
 int res;
 if (value!=valueref)
 {
   char buffer[128];
   sprintf(buffer, "%d %d", value, valueref);
   task.sendterminated("scscp1", "error_system_specific", buffer);
   res = 0;
 }
 else
 {
    res = task.sendcompleted("<OMI>1</OMI>"); 
 }
 return res;
}

/*-----------------------------------------------------------------*/
/*! send the answer : if value==valueref then 
 send a completed message  */
/*-----------------------------------------------------------------*/
static int server_sendreplycheckdouble(IncomingClient::Computation& task, double value, double valueref)
{
 int res;
 if (value!=valueref)
 {
   char buffer[128];
   sprintf(buffer, "%23.16E %23.16E", value, valueref);
   task.sendterminated("scscp1", "error_system_specific", buffer);
   res = 0;
 }
 else
 {
    res = task.sendcompleted("<OMI>1</OMI>"); 
 }
 return res;
}

/*-----------------------------------------------------------------*/
/*! process the procedure call */
/*-----------------------------------------------------------------*/
static int  processcall(IncomingClient *incomingclient,int typeanswer)
{
 int res, resopt;
 int res1=0;
 SCSCP_msgtype msgtype;
 size_t timeusage, memsize;
 int debuglevel;
 SCSCP_option_return returntype;
 static char *buffer;
 static int counter=0;
 const char *valuestr;
 int valueint, valueintref;
 const char *valuestrref;
 double valuedbl;
 static char *openmathbuffer;
 size_t len;
 OMV v;
 OMI entier;
 OMF f;
 int entiercourt;
 OMR refer;
 
 IncomingClient::Computation task(*incomingclient);
 IncomingClient::Computation task2(*incomingclient);
 Iunfstream *stream = NULL;
 res = task.recv(msgtype, stream);
 
     if (res)
     {
      const char *callid;
      task.get_callid(callid);
      switch(msgtype)
      {
       case SCSCP_msgtype_ProcedureCall : 
            /*printf("Procedure Call '%s'\n", callid);*/
            switch(typeanswer)
            {
             case 0: 
               res = task.sendcompleted("<OMI>0</OMI>"); 
               break;
               
             case 1: 
               task.set_runtime( 55);
               task.set_memory(100);
               task.set_message("my information message from libSCSCP");
               
               res = task.sendcompleted("<OMI>0</OMI>"); 
               if (res==0) printf("sendcompleted failed!\n");
               break;

             case 2: 
               res = task.sendcompleted("<OMS cd=\"alg1\" name=\"zero\" /><OMS cd=\"arith1\" name=\"abs\" />"); 
               if (res==0) printf("SCSCP_ss_sendcompletedstr failed! \n");
               break;               

             case 3: 
               res = task.sendterminated("scscp1", "error_system_specific", "unknown symbol"); 
               if (res==0) printf("SCSCP_ss_sendterminatedstr failed! .\n");
               break;
               
             case 4: 
               resopt = task.get_runtimelimit(timeusage);
               if (resopt) 
                  SCSCP_debugprint("runtime limit = %lld\n", (long long)timeusage);
              /* else 
               {
                if (SCSCP_status_is(status)==SCSCP_STATUS_USAGEUNKNOWNRUNTIME)
                  SCSCP_debugprint("runtime limit not available\n");
                else res = 0;
               }*/
               resopt = task.get_minmemory(memsize);
               if (resopt) 
                  SCSCP_debugprint("minimum memory = %lld\n", (long long)memsize);
              /* else 
               {
                if (SCSCP_status_is(status)==SCSCP_STATUS_USAGEUNKNOWNMINMEMORY)
                  SCSCP_debugprint("minimum memory not available\n");
                else res = 0;
               }*/
               
               resopt = task.get_maxmemory(memsize);
               if (resopt) 
                  SCSCP_debugprint("maximum memory = %lld\n", (long long)memsize);
              /* else 
               {
                if (SCSCP_status_is(status)==SCSCP_STATUS_USAGEUNKNOWNMAXMEMORY)
                  SCSCP_debugprint("maximum memory not available\n");
                else res = 0;
               }*/
               
               resopt = task.get_debuglevel(debuglevel);
               if (resopt) 
                  SCSCP_debugprint("debug level = %d\n", debuglevel);
               /*else 
               {
                if (SCSCP_status_is(status)==SCSCP_STATUS_USAGEUNKNOWNDEBUGLEVEL)
                  SCSCP_debugprint("debug level not available\n");
                else res = 0;
               }*/
               
               resopt = task.get_returntype(returntype);
               if (resopt) 
                  SCSCP_debugprint("return type = %d\n", (int)returntype);
               /*else 
               {
                if (SCSCP_status_is(status)==SCSCP_STATUS_USAGEUNKNOWNRETURNTYPE)
                  SCSCP_debugprint("return type not available\n");
                else res = 0;
               }*/
               
               res = task.sendcompleted("<OMI>0</OMI>"); 
               if (res==0) printf("SCSCP_ss_sendcompletedstr failed! \n");
               break;               

             case 6: 
               res = task.sendinfomessage("debugging command from server"); 
               if (res==0) printf("sendinfomessage failed!\n");
               if (strncmp(callid,"libSCSCP",strlen("libSCSCP"))==0)
               {
               res = task.sendcompleted("<OMI>0</OMI>"); 
               }
               else
               {
                res = task.sendterminated( "scscp1", "error_system_specific",
                           "bad call ID name"); 
               }
               break; 
               
             case 7: 
               res = task2.recv(msgtype, openmathbuffer, len);
               if (msgtype!=SCSCP_msgtype_Interrupt )
               {
                res = task.sendterminated("scscp1", "error_system_specific",
                           "msgtype must be SCSCP_msgtype_Interrupt"); 
               }
               else
               {
                const char *newcallidinter;
                res = task2.get_callid(newcallidinter);
                if (strcmp(newcallidinter,callid)!=0) 
                {
                 printf("invalid call id: %s %s\n", newcallidinter,callid);
                 res = 0;
                } 
                res1 = task.sendcompleted("<OMI>0</OMI>"); 
                if (res) res = res1;
               }
               break; 
               
 
             case 10: 
               res = task.sendcompleted("<OMF dec=\"1.0\" />"); 
               break;

             case 11: 
               res = task.sendcompleted("<OMV name=\"myvar\" />"); 
               break;

             case 12: 
               if (counter==0)
               {
                res = task.sendcompleted("<OM:OMI  xmlns:OM=\"http://www.openmath.org/OpenMath\" >1</OM:OMI>"); 
                counter++;
               }
               else
               {
                res = task.sendcompleted("<OM:OMI  xmlns:OM=\"http://www.openmath.org/OpenMath\" >2</OM:OMI>"); 
               }
               break;

            case 13:
               ( stream->beginOM()) >> v;
               res = server_sendreplycheck(task, v.get_name(), "xy");
               break;

            case 14:
               ( stream->beginOM()) >> v;
               res = server_sendreplycheck(task, v.get_name(), getlongstring());
               break;

            case 15: valueintref = 1;
            case 16: if (typeanswer==16) valueintref = 127;
            case 17: if (typeanswer==17) valueintref = 32768;
            case 18: if (typeanswer==18) valueintref = 2147483647;
            case 19: if (typeanswer==19) valueintref = -2147483647-1; /*-2147483648; : remove a warning from gcc */
               ( stream->beginOM()) >> valueint;
               res = server_sendreplycheckint(task, valueint, valueintref);
               break;

            case 20: valuestrref = "+1125899906842624";
            case 21: if (typeanswer==21) valuestrref = "-1125899906842624";
            case 22: if (typeanswer==22) valuestrref = "+1125899906842624";
               ( stream->beginOM()) >> entier;
               res = server_sendreplycheck(task, entier.get_value(), valuestrref);
               break;

            case 23:
               ( stream->beginOM()) >> valuedbl;
               res = server_sendreplycheckdouble(task, valuedbl, 1.0E-10);
               break;

            case 24: valuestrref = "1234567890";
            case 25: if (typeanswer==25) valuestrref = getlongstring();
               ( stream->beginOM()) >> valuestr;
               res = server_sendreplycheck(task,  valuestr, valuestrref);
               break;

            case 26: valuestrref = "scscp://test1";
            case 27: if (typeanswer==27) valuestrref = getlongstring();
               ( stream->beginOM()) >> refer;
               res = server_sendreplycheck(task, refer.get_reference(), valuestrref);
               break;

            }
            break;

       default :
            printf("unknown message type !!!\n"); 
            res = 0;
            break;
      }
     }
     else
     {
      /*printf("SCSCP_ss_callrecvheader failed!\n");*/
      /* if client close the connection => return -1 */
      /*if (incomingclient->eof()) res = -1; */
     }
 return res;
}

/*-----------------------------------------------------------------*/
/*! main program */
/*-----------------------------------------------------------------*/
int main(int argc, char *argv[])
{
/* printf("scscpservertest started with %d\n", atoi(argv[1]));*/
 return runserver(atoi(argv[1]), argc==3?atoi(argv[2]):-1);
}
