/*--------------------------------------------------------------------------

	The ObjectFactory.
	
	See .h file what it does.
	


	Mark Koennecke,    November 1996

	Copyright:

	Labor fuer Neutronenstreuung
	Paul Scherrer Institut
	CH-5423 Villigen-PSI


        The authors hereby grant permission to use, copy, modify, distribute,
        and license this software and its documentation for any purpose, provided
        that existing copyright notices are retained in all copies and that this
        notice is included verbatim in any distributions. No written agreement,
        license, or royalty fee is required for any of the authorized uses.
        Modifications to this software may be copyrighted by their authors
        and need not follow the licensing terms described here, provided that
        the new terms are clearly indicated on the first page of each file where
        they apply.

        IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY
        FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
        ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY
        DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE
        POSSIBILITY OF SUCH DAMAGE.

        THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
        INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE
        IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
        NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
        MODIFICATIONS.
-----------------------------------------------------------------------------*/
#include <stdlib.h>
#include <assert.h>
#include "fortify.h"
#include "ifile.h"
#include "sicsexit.h"
#include "obdes.h"
#include "interface.h"
#include "passwd.h"
#include "conman.h"
#include "macro.h"
#include "splitter.h"
#include "SCinter.h"
#include "sicsvar.h"
#include "drive.h"
#include "motor.h"
#include "servlog.h"
#include "nserver.h"
#include "status.h"
#include "configfu.h"
#include "devexec.h"
#include "mumo.h"
#include "selector.h"
#include "selvar.h"
#include "countdriv.h"
#include "counter.h"
#include "buffer.h"
#include "scan.h"
#include "script.h"
#include "o2t.h"
#include "alias.h"
#include "dmc.h"
#include "stringdict.h"
#include "HistMem.h"
#include "velo.h"
#include "emon.h"
#include "evcontroller.h"
#include "danu.h"
#include "nserver.h"
#include "scan.h"
#include "fitcenter.h"
#include "token.h"
#include "serial.h"
#include "hkl.h"
#include "optimise.h"
#include "nextrics.h"
#include "mesure.h"
#include "commandlog.h"
#include "sps.h"
#include "udpquieck.h"
#include "pimotor.h"
#include "sanswave.h"
#include "faverage.h"
#include "fowrite.h"
#include "choco.h"
#include "chadapter.h"
#include "hklscan.h"
#include "xytable.h"
#include "amor2t.h"
#include "nxamor.h"
#include "amorstat.h"
#include "maximize.h"
#include "difrac.h"
#include "sicscron.h"
#include "lin2ang.h"
/*----------------------- Server options creation -------------------------*/
  static int IFServerOption(SConnection *pCon, SicsInterp *pSics, void *pData,
                     int argc, char *argv[])
  {
     char pBueffel[512];
     
     assert(pSics);
     assert(pCon);

     /* check authorisation */
     if(!SCMatchRights(pCon,usMugger))
     {
       SCWrite(pCon,"Insufficient privilege to set options",eError);
       return 0;
     }
     
     /* test if sufficient arguments */
     if(argc < 3)
     {
       sprintf(pBueffel,"Syntax: %s name value ", argv[0]);
       SCWrite(pCon,pBueffel,eError);
       return 0;
     }
     
     /* just do it */
     pSICSOptions = IFAddOption(pSICSOptions,argv[1],argv[2]);
     return 1; 
  } 
/*----------------------- Password database update -------------------------*/
  static int PWSicsUser(SConnection *pCon, SicsInterp *pSics, void *pData,
                     int argc, char *argv[])
  {			
     char pBueffel[512];
     TokenList *pList = NULL;
     
     assert(pSics);
     assert(pCon);

     /* check authorisation */
     if(SCGetRights(pCon) > usMugger)
     {
       SCWrite(pCon,"Insufficient privilege to set users",eError);
       return 0;
     }
     
     /* analyse commandlist */
     pList = SplitArguments(argc-1, &argv[1]);
     if( (!pList) || (!pList->pNext) || (!pList->pNext->pNext) )
     {
         sprintf(pBueffel,"Invalid Passwd Entry ::\n %s %s %s\n", argv[1],
                           argv[2], argv[3]);
         SCWrite(pCon,pBueffel,eError);                  
         DeleteTokenList(pList);
         return 0;
     }
     else
     {
         if(pList->pNext->pNext->Type != eInt)
         {
            SCWrite(pCon,"Need integer rights code",eError);
            DeleteTokenList(pList);
            return 0;
         }
         else
         {
            AddUser(pList->text, pList->pNext->text,
                    pList->pNext->pNext->iVal);
          }
       }
       DeleteTokenList(pList);
       return 1;
  } 
/*-------------------------------------------------------------------------*/
  int InitSANS(SConnection *pCon, SicsInterp *pSics, void *pData, 
               int argc, char *argv[]); 
/*--------------------------------------------------------------------------*/                   
  static void InitIniCommands(SicsInterp *pInter,pTaskMan pTask)
  {
    pExeList pExe;
    pEnvMon pEnv = NULL;
    assert(pInter);
    
    pExe = CreateExeList(pTask);
    pEnv = CreateEnvMon();
    
    assert(pExe);
    assert(pEnv);
    
    /* permanent commands */
     AddCommand(pInter,"Sics_Exitus",SicsExit,NULL,NULL);
     AddCommand(pInter,"FileEval",MacroFileEval,NULL,NULL);
     AddCommand(pInter,"InternEval",InternalFileEval,NULL,NULL);
     AddCommand(pInter,"FileWhere",MacroWhere,WhereKill,NULL);
     AddCommand(pInter,"ClientPut",ClientPut,NULL,NULL);
     AddCommand(pInter,"transact",TransactAction,NULL,NULL);
     AddCommand(pInter,"sicsprompt", SicsPrompt,NULL,NULL);
     AddCommand(pInter,"Publish",TclPublish,NULL,NULL);
     AddCommand(pInter,"GetLog",  LogCapture,NULL,NULL);
     AddCommand(pInter,"config",  ConfigCon,NULL,NULL);
     AddCommand(pInter,"wait",  UserWait,NULL,NULL);
     AddCommand(pInter,"status",  UserStatus,NULL,NULL);
     AddCommand(pInter,"ResetServer",ResetStatus,NULL,NULL);
     AddCommand(pInter,"Dir",ListObjects,NULL,NULL);    
     AddCommand(pInter,"Backup",BackupStatus,NULL,NULL);
     AddCommand(pInter,"Restore",RestoreStatus,NULL,NULL);
     AddCommand(pInter,"SetInt", SetSICSInterrupt,NULL,NULL);
     AddCommand(pInter,"GetInt",GetSICSInterrupt,NULL,NULL);
     AddCommand(pInter,"SICSType",SICSType,NULL,NULL);
     AddCommand(pInter,"SICSBounds",SICSBounds,NULL,NULL);
     AddCommand(pInter,"SICSStatus",SICSStatus,NULL,NULL);
     AddCommand(pInter,"sicstime",SICSTime,NULL,NULL);
     AddCommand(pInter,"SetStatus",SetSICSStatus,NULL,NULL);
     AddCommand(pInter,"db",SICSDebug,NULL,NULL);
     AddCommand(pInter,"EVFactory",EVControlFactory,NULL,NULL);
     AddCommand(pInter,"emon",EVWrapper,DeleteEnvMon,pEnv);
     AddCommand(pInter,"commandlog",CommandLog,CommandLogClose,NULL);
     AddCommand(pInter,"udpquieck",QuieckAction,KillQuieck,NULL);
     AddCommand(pInter,"alias",MakeAlias,NULL,NULL);
     AddCommand(pInter,"sicscron",MakeCron,NULL,NULL);

     /* commands to do with the executor. Only StopExe carries the
        DeleteFunction in order to avoid double deletion. All the
        other commands operate on the same datastructure.
     */
     AddCommand(pInter,"StopExe",StopCommand,DeleteExeList, pExe);
     AddCommand(pInter,"ListExe",ListExe,NULL,pExe);
     AddCommand(pInter,"Success",Success,NULL,pExe);

    /* add additional object creation commands here */
    AddCommand(pInter,"TokenInit",TokenInit,NULL,NULL);
    AddCommand(pInter,"ServerOption",IFServerOption,NULL,NULL);
    AddCommand(pInter,"SicsUser", PWSicsUser,NULL,NULL); 
    AddCommand(pInter,"VarMake",VarFactory,NULL,NULL);
    AddCommand(pInter,"MakeDrive",MakeDrive,NULL,NULL);
    AddCommand(pInter,"Motor",MotorCreate,NULL,NULL);
    AddCommand(pInter,"MakeMulti",MakeMulti,NULL,NULL);
    AddCommand(pInter,"MakeMono",MonoInit,NULL,NULL);
    AddCommand(pInter,"MakeWaveLength",MakeWaveLengthVar,NULL,NULL);
    AddCommand(pInter,"MakeEnergy",MakeEnergyVar,NULL,NULL);
    AddCommand(pInter,"MakeCounter",MakeCounter,NULL,NULL);
    AddCommand(pInter,"MakeRuenBuffer",InitBufferSys,NULL,NULL);
    AddCommand(pInter,"MakeO2T",CreateO2T,NULL,NULL);
    AddCommand(pInter,"SicsAlias",SicsAlias,NULL,NULL);
    AddCommand(pInter,"InitDMC",InitDmc,NULL,NULL);
    AddCommand(pInter,"InitSANS",InitSANS,NULL,NULL);
    AddCommand(pInter,"MakeHM",MakeHistMemory,NULL,NULL);
    AddCommand(pInter,"VelocitySelector",VelSelFactory,NULL,NULL);
    AddCommand(pInter,"MakeDataNumber",DNFactory,NULL,NULL);
    AddCommand(pInter,"MakeScanCommand",ScanFactory,NULL,NULL);
    AddCommand(pInter,"MakePeakCenter",FitFactory,NULL,NULL);
    AddCommand(pInter,"SerialInit",SerialInit,NULL,NULL);
    AddCommand(pInter,"MakeHKL",HKLFactory,NULL,NULL);
    AddCommand(pInter,"MakeOptimise",MakeOptimiser,NULL,NULL);
    AddCommand(pInter,"MakeTRICSNEXUS",NexTricsFactory,NULL,NULL);
    AddCommand(pInter,"MakeMesure",MesureFactory,NULL,NULL);
    AddCommand(pInter,"MakeSPS",SPSFactory,NULL,NULL);
    AddCommand(pInter,"MakePIMotor",PIMotorFactory,NULL,NULL);
    AddCommand(pInter,"MakeSANSWave",MakeSANSWave,NULL,NULL);
    AddCommand(pInter,"MakeFocusAverager",MakeFA,NULL,NULL);
    AddCommand(pInter,"kill_command",SICSKill,NULL,NULL);
    AddCommand(pInter,"FocusInstall",FoInstall,NULL,NULL);
    AddCommand(pInter,"MakeChopper",ChocoFactory,NULL,NULL);
    AddCommand(pInter,"ChopperAdapter",CHAdapterFactory,NULL,NULL);
    AddCommand(pInter,"MakeHklscan",HklscanFactory,NULL,NULL);
    AddCommand(pInter,"MakeXYTable",XYFactory,NULL,NULL);
    AddCommand(pInter,"MakeAmor2T",Amor2TFactory,NULL,NULL);
    AddCommand(pInter,"MakeStoreAmor",AmorStoreMake,NULL,NULL);
    AddCommand(pInter,"MakeAmorStatus",AmorStatusFactory,NULL,NULL);
    AddCommand(pInter,"MakeMaximize",MaximizeFactory,NULL,NULL);
    AddCommand(pInter,"MakeDifrac",MakeDifrac,NULL,NULL);
    AddCommand(pInter,"MakeLin2Ang",MakeLin2Ang,NULL,NULL);
  } 
/*---------------------------------------------------------------------------*/
  static  void KillIniCommands(SicsInterp *pSics)
  {
  
    /* specify superfluous initialization commands here */
    RemoveCommand(pSics,"TokenInit");
    RemoveCommand(pSics,"ServerOption");
    RemoveCommand(pSics,"SicsUser");
    RemoveCommand(pSics,"VarMake");
    RemoveCommand(pSics,"MakeDrive");
    RemoveCommand(pSics,"Motor");
/*
    RemoveCommand(pSics,"MakeMulti");
*/    
    RemoveCommand(pSics,"MakeMono");
    RemoveCommand(pSics,"MakeWaveLength");
    RemoveCommand(pSics,"MakeEnergy");
    RemoveCommand(pSics,"MakeCounter");
    RemoveCommand(pSics,"MakeRuenBuffer");
    RemoveCommand(pSics,"MakeScan");
    RemoveCommand(pSics,"MakeO2T");
    RemoveCommand(pSics,"SicsAlias");
    RemoveCommand(pSics,"InitDMC");
    RemoveCommand(pSics,"InitSANS");
    RemoveCommand(pSics,"MakeHM");
    RemoveCommand(pSics,"VelocitySelector");
    RemoveCommand(pSics,"MakeDataNumber");
    RemoveCommand(pSics,"MakeScanCommand");
    RemoveCommand(pSics,"MakePeakCenter");
    RemoveCommand(pSics,"SerialInit");
    RemoveCommand(pSics,"MakeHKL");
    RemoveCommand(pSics,"MakeOptimiser");
    RemoveCommand(pSics,"MakeTRICSNEXUS");
    RemoveCommand(pSics,"MakeMesure");
    RemoveCommand(pSics,"MakeSPS");
    RemoveCommand(pSics,"MakePIMotor");
    RemoveCommand(pSics,"MakeSANSWave");
    RemoveCommand(pSics,"MakeFocusAverager");
    RemoveCommand(pSics,"FocusInstall");
    RemoveCommand(pSics,"MakeChopper");
    RemoveCommand(pSics,"ChopperAdapter");
    RemoveCommand(pSics,"MakeHklscan");
    RemoveCommand(pSics,"MakeXYTable");
    RemoveCommand(pSics,"MakeAmor2T");
    RemoveCommand(pSics,"MakeStoreAmor");
    RemoveCommand(pSics,"MakeAmorStatus");
    RemoveCommand(pSics,"MakeMaximize");
    RemoveCommand(pSics,"MakeDifrac");
    RemoveCommand(pSics,"MakeLin2Ang");
  }
  
   
/*--------------------------------------------------------------------------*/

  int InitObjectCommands(pServer pServ, char *file)
  {
     SConnection *pCon = NULL;
     char pBueffel[1024];
     int iRet;
     SicsInterp *pSics;
     
     pSics = pServ->pSics;
     assert(pSics);
     
     /* general initialization */
     InitIniCommands(pSics,pServ->pTasker);
     
     /* create a connection  */
     pCon = SCCreateDummyConnection(pSics);
     if(!pCon)
     {
       return 0;
     }
     pCon->iFiles = 1;
     pCon->pFiles[0] = stdout;
     
     /* evaluate the file */
     sprintf(pBueffel,"fileeval %s",file);
     iRet = InterpExecute(pSics,pCon,pBueffel);
     if(!iRet)
     {
        KillIniCommands(pSics);
        SCDeleteConnection(pCon);
        return 0;
     }
     
     /* done */
     pCon->iFiles = 0;
     SCDeleteConnection(pCon);
     KillIniCommands(pSics);
     return 1;
  }  

