/****************************************************************************
 * This file is part of the project AqHome.
 * AqHome (c) by 2025 Martin Preuss, all rights reserved.
 *
 * The license for this file can be found in the file COPYING which you
 * should have received along with this file.
 ****************************************************************************/

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif


#include "./server_p.h"
#include "./s_connect.h"
#include "./s_getdevices.h"
#include "./s_getvalues.h"
#include "./s_addvalue.h"
#include "./s_annvalue.h"
#include "./s_updatedata.h"
#include "./s_setdata.h"
#include "./s_getdatapoints.h"
#include "./s_moddevice.h"

#include <aqhome/aqhome.h>
#include <aqhome/ipc2/ipc_server.h>
#include <aqhome/ipc2/tcpd_object.h>
#include <aqhome/msg/ipc/m_ipc.h>
#include <aqhome/msg/ipc/m_ipc_result.h>
#include <aqhome/msg/ipc/m_ipc_tag16.h>
#include <aqhome/msg/ipc/data/m_ipcd.h>

#include <gwenhywfar/args.h>
#include <gwenhywfar/misc.h>
#include <gwenhywfar/debug.h>

#include <fcntl.h>
#include <unistd.h>
#include <errno.h>



/* ------------------------------------------------------------------------------------------------
 * defines
 * ------------------------------------------------------------------------------------------------
 */

#define I18N(msg) msg
#define I18S(msg) msg



enum {
  AQH_AQHOME_SERVER_SLOT_NEWCLIENT=1,
  AQH_AQHOME_SERVER_SLOT_CLOSED
};



/* ------------------------------------------------------------------------------------------------
 * global vars
 * ------------------------------------------------------------------------------------------------
 */

GWEN_INHERIT(AQH_OBJECT, AQHOME_SERVER)



/* ------------------------------------------------------------------------------------------------
 * forward declarations
 * ------------------------------------------------------------------------------------------------
 */

static void GWENHYWFAR_CB _freeData(void *bp, void *p);
static int _setupStorage(AQHOME_SERVER *xo, GWEN_DB_NODE *dbArgs);
static int _setupIpc(AQH_OBJECT *o, AQHOME_SERVER *xo, GWEN_DB_NODE *dbArgs);
static int _handleSignal(AQH_OBJECT *o, uint32_t slotId, AQH_OBJECT *senderObject, int param1, void *param2);
static int _handleNewClient(AQH_OBJECT *o, AQH_OBJECT *clientEndpoint);
static int _handleClientDown(AQH_OBJECT *o, AQH_OBJECT *clientEndpoint);
static void _handleMsgsFromClient(AQH_OBJECT *o, AQHOME_SERVER *xo, AQH_OBJECT *ep);
static void _handleMsgFromClient(AQH_OBJECT *o, AQH_OBJECT *ep, const AQH_MESSAGE *msg);
static void _createValue(AQHOME_SERVER *xo, AQH_OBJECT *epDriver,
			 const char *deviceName, const char *valueNameForSystem, const AQH_VALUE *valueTemplate);
static void _updateValue(AQHOME_SERVER *xo, AQH_VALUE *v, const char *deviceName, const AQH_VALUE *valueTemplate);
static AQH_DEVICE *_getOrCreateDeviceForDriver(AQHOME_SERVER *xo, AQH_OBJECT *epDriver, const char *deviceName);
static int _createPidFile(const char *pidFilename);
static int _readArgs(int argc, char **argv, GWEN_DB_NODE *dbArgs);



/* ------------------------------------------------------------------------------------------------
 * implementation
 * ------------------------------------------------------------------------------------------------
 */

AQH_OBJECT *AqHomeDataServer_new(AQH_EVENT_LOOP *eventLoop)
{
  AQH_OBJECT *o;
  AQHOME_SERVER *xo;

  o=AQH_Object_new(eventLoop);
  GWEN_NEW_OBJECT(AQHOME_SERVER, xo);
  GWEN_INHERIT_SETDATA(AQH_OBJECT, AQHOME_SERVER, o, xo, _freeData);
  xo->storageMutex=GWEN_Mutex_new();
  xo->tcpClientList=AQH_Object_List_new();
  xo->requestTree=AQH_MsgRequest_new();

  AQH_Object_SetSignalHandlerFn(o, _handleSignal);

  return o;
}



void GWENHYWFAR_CB _freeData(GWEN_UNUSED void *bp, void *p)
{
  AQHOME_SERVER *xo;

  xo=(AQHOME_SERVER*) p;
  GWEN_Mutex_free(xo->storageMutex);
  if (xo->ipcServer) {
    AQH_Object_Disable(xo->ipcServer);
    AQH_Object_free(xo->ipcServer);
    xo->ipcServer=NULL;
  }
  if (xo->tcpClientList) {
    AQH_Object_List_free(xo->tcpClientList);
    xo->tcpClientList=NULL;
  }
  GWEN_DB_Group_free(xo->dbArgs);
  AQH_Storage_free(xo->storage);
  AQH_MsgRequest_free(xo->requestTree);
  free(xo->pidFile);

  GWEN_FREE_OBJECT(xo);
}



/* xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
 * getters, setters
 * xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
 */

AQHOME_SERVER *AqHomeDataServer_GetServerData(const AQH_OBJECT *o)
{
  AQHOME_SERVER *xo;

  xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQHOME_SERVER, o);
  return xo;
}



int AqHomeDataServer_GetTimeout(const AQH_OBJECT *o)
{
  AQHOME_SERVER *xo;

  xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQHOME_SERVER, o);
  if (xo)
    return xo->timeout;
  return 0;
}



int AqHomeDataServer_GetClientNum(const AQH_OBJECT *o)
{
  AQHOME_SERVER *xo;

  xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQHOME_SERVER, o);
  if (xo)
    return AQH_Object_List_GetCount(xo->tcpClientList);
  return 0;
}



/* xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
 * init
 * xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
 */

int AqHomeDataServer_Init(AQH_OBJECT *o, int argc, char **argv)
{
  AQHOME_SERVER *xo;

  xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQHOME_SERVER, o);
  if (xo) {
    GWEN_DB_NODE *dbArgs;
    int rv;
    const char *s;

    dbArgs=GWEN_DB_Group_new("args");
    rv=_readArgs(argc, argv, dbArgs);
    if (rv<0) {
      DBG_ERROR(NULL, "Error reading args (%d)", rv);
      return rv;
    }
    AQH_MergeConfigFileIntoConfig(dbArgs, "ConfigFile");

    xo->dbArgs=dbArgs;

    s=GWEN_DB_GetCharValue(dbArgs, "loglevel", 0, NULL);
    if (s && *s) {
      GWEN_LOGGER_LEVEL ll;

      ll=GWEN_Logger_Name2Level(s);
      GWEN_Logger_SetLevel(NULL, ll);
    }

    xo->timeout=GWEN_DB_GetIntValue(dbArgs, "timeout", 0, 0);

    s=GWEN_DB_GetCharValue(dbArgs, "pidfile", 0, AQHOME_DATA_DEFAULT_PIDFILE);
    if (s && *s) {
      free(xo->pidFile);
      xo->pidFile=strdup(s);
      rv=_createPidFile(s);
      if (rv<0) {
        DBG_ERROR(NULL, "Error creating PID file (%d)", rv);
        return rv;
      }
    }

    rv=_setupStorage(xo, dbArgs);
    if (rv<0) {
      DBG_INFO(NULL, "here (%d)", rv);
      return rv;
    }

    rv=_setupIpc(o, xo, dbArgs);
    if (rv<0) {
      DBG_INFO(NULL, "here (%d)", rv);
      return rv;
    }

    return 0;
  }
  else {
    DBG_ERROR(NULL, "Not of type AQHOME_SERVER object");
    return GWEN_ERROR_INVALID;
  }
}



int _setupStorage(AQHOME_SERVER *xo, GWEN_DB_NODE *dbArgs)
{
  const char *dataFolder;
  GWEN_BUFFER *nameBuf;
  AQH_STORAGE *sto;
  int rv;

  dataFolder=GWEN_DB_GetCharValue(dbArgs, "dataFolder", 0, AQHOME_DATA_DEFAULT_DATADIR);
  nameBuf=GWEN_Buffer_new(0, 256, 0, 1);
  GWEN_Buffer_AppendArgs(nameBuf, "%s%s%s", dataFolder, GWEN_DIR_SEPARATOR_S, AQHOME_DATA_STATEFILENAME);

  sto=AQH_Storage_new();
  AQH_Storage_SetStateFile(sto, GWEN_Buffer_GetStart(nameBuf));
  AQH_Storage_SetDataFileFolder(sto, dataFolder);
  GWEN_Buffer_free(nameBuf);

  rv=AQH_Storage_Init(sto);
  if (rv<0) {
    DBG_INFO(NULL, "here (%d)", rv);
    AQH_Storage_free(sto);
    return rv;
  }
  xo->storage=sto;
  return 0;
}



int _setupIpc(AQH_OBJECT *o, AQHOME_SERVER *xo, GWEN_DB_NODE *dbArgs)
{
  const char *tcpAddress;
  int tcpPort;

  tcpAddress=GWEN_DB_GetCharValue(dbArgs, "tcpAddress", 0, NULL);
  if (!(tcpAddress && *tcpAddress))
    tcpAddress=GWEN_DB_GetCharValue(dbArgs, "ConfigFile/brokerAddress", 0, NULL);

  tcpPort=GWEN_DB_GetIntValue(dbArgs, "tcpPort", 0, -1);
  if (tcpPort<0)
    tcpPort=GWEN_DB_GetIntValue(dbArgs, "ConfigFile/brokerPort", 0, AQHOME_DATA_DEFAULT_IPC_PORT);

  if (tcpAddress && *tcpAddress && tcpPort>0) {
    int fd;

    DBG_ERROR(NULL, "Starting TCP service on \"%s\":%d", tcpAddress, tcpPort);
    fd=AQH_TcpdObject_CreateListeningSocket(tcpAddress, tcpPort);
    if (fd<0) {
      DBG_INFO(NULL, "here");
      return GWEN_ERROR_IO;
    }

    xo->ipcServer=AQH_IpcServerObject_new(AQH_Object_GetEventLoop(o), fd);
    AQH_Object_AddLink(xo->ipcServer, AQH_IPC_SERVER_SIGNAL_NEWCLIENT, AQH_AQHOME_SERVER_SLOT_NEWCLIENT, o);
    AQH_Object_Enable(xo->ipcServer);
    return 0;
  }
  else {
    DBG_ERROR(NULL, "Missing server address");
    return GWEN_ERROR_GENERIC;
  }
}



/* xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
 * fini
 * xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
 */

void AqHomeDataServer_Fini(AQH_OBJECT *o)
{
  AQHOME_SERVER *xo;

  xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQHOME_SERVER, o);
  if (xo) {
    if (xo->pidFile)
      remove(xo->pidFile);
  }
}



/* xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
 * signal handler
 * xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
 */

int _handleSignal(AQH_OBJECT *o, uint32_t slotId, AQH_OBJECT *senderObject, GWEN_UNUSED int param1, void *param2)
{
  switch(slotId) {
  case AQH_AQHOME_SERVER_SLOT_NEWCLIENT: return _handleNewClient(o, (AQH_OBJECT*) param2);
  case AQH_AQHOME_SERVER_SLOT_CLOSED:    return _handleClientDown(o, senderObject);
  default:
    break;
  }

  return 0; /* not handled */
}



int _handleNewClient(AQH_OBJECT *o, AQH_OBJECT *clientEndpoint)
{
  AQHOME_SERVER *xo;

  xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQHOME_SERVER, o);
  if (xo) {
    DBG_INFO(NULL, "New IPC client");
    AQH_Object_AddLink(clientEndpoint, AQH_ENDPOINT_SIGNAL_CLOSED, AQH_AQHOME_SERVER_SLOT_CLOSED, o);
    AQH_Object_List_Add(clientEndpoint, xo->tcpClientList);
    return 1; /* handled */
  }

  return 0; /* not handled */
}



int _handleClientDown(AQH_OBJECT *o, AQH_OBJECT *clientEndpoint)
{
  AQHOME_SERVER *xo;

  xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQHOME_SERVER, o);
  if (xo) {
    DBG_INFO(NULL, "IPC client down");
    AQH_Object_AddFlags(clientEndpoint, AQH_OBJECT_FLAGS_DELETE);
    return 1; /* handled */
  }

  return 0; /* not handled */
}



/* xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
 * client management functions
 * xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
 */

void AqHomeDataServer_CleanupClients(AQH_OBJECT *o)
{
  AQHOME_SERVER *xo;

  xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQHOME_SERVER, o);
  if (xo) {
    AQH_OBJECT *ep;

    ep=AQH_Object_List_First(xo->tcpClientList);
    while(ep) {
      AQH_OBJECT *epNext;

      epNext=AQH_Object_List_Next(ep);
      if (AQH_Object_GetFlags(ep) & AQH_OBJECT_FLAGS_DELETE) {
        AQH_Object_List_Del(ep);
        AQH_Object_free(ep);
      }
      ep=epNext;
    } /* while */
  }
}



void AqHomeDataServer_HandleClientMsgs(AQH_OBJECT *o)
{
  AQHOME_SERVER *xo;

  xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQHOME_SERVER, o);
  if (xo) {
    AQH_OBJECT *ep;

    ep=AQH_Object_List_First(xo->tcpClientList);
    while(ep) {
      AQH_OBJECT *epNext;

      epNext=AQH_Object_List_Next(ep);
      _handleMsgsFromClient(o, xo, ep);
      ep=epNext;
    } /* while */
  }
}



void _handleMsgsFromClient(AQH_OBJECT *o, AQHOME_SERVER *xo, AQH_OBJECT *ep)
{
  AQH_MESSAGE *msg;

  while( (msg=AQH_Endpoint_GetNextMsgIn(ep)) ) {
    AQH_Message_SetObject(msg, ep);
    if (AQH_Request_Tree2_HandleIpcMsg(xo->requestTree, ep, msg)!=AQH_MSG_REQUEST_RESULT_HANDLED)
      _handleMsgFromClient(o, ep, msg);
    AQH_Message_free(msg);
  }
}



void _handleMsgFromClient(AQH_OBJECT *o, AQH_OBJECT *ep, const AQH_MESSAGE *msg)
{
  GWEN_TAG16_LIST *tagList;
  uint16_t code;
  uint8_t protoId;

  tagList=AQH_IpcMessageTag16_ParsePayload(msg, 0);

  code=AQH_IpcMessage_GetCode(msg);
  protoId=AQH_IpcMessage_GetProtoId(msg);
  if (protoId==AQH_IPC_PROTOCOL_DATA_ID) {
    DBG_INFO(NULL, "Received IPC packet %d (%x)", (int) code, code);
    switch(code) {
    case AQH_MSGTYPE_IPC_DATA_CONNECT_REQ:           AqHomeDataServer_HandleConnect(o, ep, msg, tagList);       break;
    case AQH_MSGTYPE_IPC_DATA_UPDATEDATA:            AqHomeDataServer_HandleUpdateData(o, ep, msg, tagList);    break;
    case AQH_MSGTYPE_IPC_DATA_GETVALUES_REQ:         AqHomeDataServer_HandleGetValues(o, ep, msg, tagList);     break;
    case AQH_MSGTYPE_IPC_DATA_GETDATA_REQ:           AqHomeDataServer_HandleGetDataPoints(o, ep, msg, tagList); break;
    case AQH_MSGTYPE_IPC_DATA_SETDATA:               AqHomeDataServer_HandleSetData(o, ep, msg, tagList);       break;
    case AQH_MSGTYPE_IPC_DATA_ADDVALUE:              AqHomeDataServer_HandleAddValue(o, ep, msg, tagList);      break;
    case AQH_MSGTYPE_IPC_DATA_ANNOUNCEVALUE:         AqHomeDataServer_HandleAnnounceValue(o, ep, msg, tagList); break;
    case AQH_MSGTYPE_IPC_DATA_GETDEVICES_REQ:        AqHomeDataServer_HandleGetDevices(o, ep, msg, tagList);    break;
    case AQH_MSGTYPE_IPC_DATA_MODDEVICE_REQ:         AqHomeDataServer_HandleModDevice(o, ep, msg, tagList);     break;
    default:                                         break;
    }
  }
  else {
    DBG_ERROR(NULL, "Invalid IPC protocol %d (%02x)", protoId, protoId);
  }
  GWEN_Tag16_List_free(tagList);
}



AQH_OBJECT *AqHomeDataServer_GetIpcEndpointByServiceName(const AQH_OBJECT *o, const char *serviceName)
{
  AQHOME_SERVER *xo;

  xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQHOME_SERVER, o);
  if (xo) {
    AQH_OBJECT *ep;

    ep=AQH_Object_List_First(xo->tcpClientList);
    while(ep) {
      const char *s;

      s=AQH_Endpoint_GetServiceName(ep);
      if (s && *s && strcasecmp(s, serviceName)==0)
        return ep;
      ep=AQH_Object_List_Next(ep);
    }
  }
  return NULL;
}



void AqHomeDataServer_SendResponseResultToEndpoint(AQH_OBJECT *ep, uint32_t refMsgId, int result)
{
  AQH_MESSAGE *msg;

  msg=AQH_IpcMessageResult_new(AQH_IPC_PROTOCOL_DATA_ID, AQH_IPC_PROTOCOL_DATA_VERSION, AQH_MSGTYPE_IPC_DATA_RESULT,
                               AQH_Endpoint_GetNextMessageId(ep), refMsgId, result, NULL);
  AQH_Endpoint_AddMsgOut(ep, msg);
}



/* xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
 * request management functions
 * xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
 */

AQH_MSG_REQUEST *AqHomeDataServer_GetRequestTree(const AQH_OBJECT *o)
{
  AQHOME_SERVER *xo;

  xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQHOME_SERVER, o);
  if (xo)
    return xo->requestTree;
  return NULL;
}



void AqHomeDataServer_AddRequestToTree(AQH_OBJECT *o, AQH_MSG_REQUEST *rq)
{
  AQHOME_SERVER *xo;

  xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQHOME_SERVER, o);
  if (xo && rq)
    AQH_MsgRequest_Tree2_AddChild(xo->requestTree, rq);
}



void AqHomeDataServer_CleanupRequests(AQH_OBJECT *o)
{
  AQHOME_SERVER *xo;

  xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQHOME_SERVER, o);
  if (xo) {
    AQH_Request_Tree2_CheckTimeouts(xo->requestTree);
    AQH_Request_Tree2_Cleanup(xo->requestTree);
  }
}



/* xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
 * storage management functions
 * xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
 */

int AqHomeDataServer_LockStorage(AQH_OBJECT *o)
{
  AQHOME_SERVER *xo;

  xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQHOME_SERVER, o);
  if (xo) {
    int rv;

    rv=GWEN_Mutex_Lock(xo->storageMutex);
    if (rv<0) {
      DBG_ERROR(AQH_LOGDOMAIN, "Error obtaining lock on storage mutex");
      return rv;
    }
    return rv;
  }
  return GWEN_ERROR_INVALID;
}



int AqHomeDataServer_UnlockStorage(AQH_OBJECT *o)
{
  AQHOME_SERVER *xo;

  xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQHOME_SERVER, o);
  if (xo) {
    int rv;

    rv=GWEN_Mutex_Unlock(xo->storageMutex);
    if (rv<0) {
      DBG_ERROR(AQH_LOGDOMAIN, "Error releasing lock on storage mutex");
      return rv;
    }
    return rv;
  }
  return GWEN_ERROR_INVALID;
}



int AqHomeDataServer_WriteStorageIfChanged(AQH_OBJECT *o)
{
  AQHOME_SERVER *xo;

  xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQHOME_SERVER, o);
  if (xo) {
    if (AQH_Storage_GetRuntimeFlags(xo->storage) & AQH_STORAGE_RTFLAGS_MODIFIED) {
      int rv;

      DBG_INFO(NULL, "Storage modified, writing statefile");
      rv=AqHomeDataServer_LockStorage(o);
      if (rv<0) {
        DBG_INFO(NULL, "Error locking storage (%d)", rv);
        return rv;
      }
      rv=AQH_Storage_WriteState(xo->storage);
      if (rv<0) {
        DBG_INFO(NULL, "Error writing state file (%d)", rv);
        AqHomeDataServer_UnlockStorage(o);
        return rv;
      }

      rv=AqHomeDataServer_UnlockStorage(o);
      if (rv<0) {
        DBG_INFO(NULL, "Error unlocking storage (%d)", rv);
        return rv;
      }
    }

    return 0;
  }
  return GWEN_ERROR_INVALID;
}



AQH_VALUE *AqHomeDataServer_GetOrCreateValueForDriverWithTemplate(AQH_OBJECT *o, AQH_OBJECT *epDriver, const AQH_VALUE *valueTemplate)
{
  AQHOME_SERVER *xo;

  xo=GWEN_INHERIT_GETDATA(AQH_OBJECT, AQHOME_SERVER, o);
  if (xo) {
    const char *serviceName;
    AQH_VALUE *v;
    GWEN_BUFFER *buf;
    const char *valueName;
    const char *deviceName;

    serviceName=AQH_Endpoint_GetServiceName(epDriver);
    valueName=AQH_Value_GetName(valueTemplate);
    deviceName=AQH_Value_GetDeviceName(valueTemplate);

    buf=GWEN_Buffer_new(0, 256, 0, 1);
    if (deviceName && *deviceName)
      GWEN_Buffer_AppendArgs(buf, "%s/%s/%s", (serviceName && *serviceName)?serviceName:"unknown", deviceName, valueName);
    else
      GWEN_Buffer_AppendArgs(buf, "%s/%s", (serviceName && *serviceName)?serviceName:"unknown", valueName);

    v=AQH_Storage_GetValueByNameForSystem(xo->storage, GWEN_Buffer_GetStart(buf));
    if (v==NULL) {
      if (AQH_Endpoint_GetPermissions(epDriver) & AQH_ENDPOINT_PERMS_ADDVALUE)
	_createValue(xo, epDriver, deviceName, GWEN_Buffer_GetStart(buf), valueTemplate);
      else {
        DBG_ERROR(AQH_LOGDOMAIN, "No permissions to create value \"%s\"", GWEN_Buffer_GetStart(buf));
        GWEN_Buffer_free(buf);
        return NULL;
      }
    }
    else
      _updateValue(xo, v, GWEN_Buffer_GetStart(buf), valueTemplate);
    GWEN_Buffer_free(buf);
    return v;
  }
  return NULL;
}



void _createValue(AQHOME_SERVER *xo, AQH_OBJECT *epDriver,
		  const char *deviceName, const char *valueNameForSystem, const AQH_VALUE *valueTemplate)
{
  AQH_DEVICE *device;
  const char *serviceName;
  const char *valueName;
  AQH_VALUE *v;

  serviceName=AQH_Endpoint_GetServiceName(epDriver);
  valueName=AQH_Value_GetName(valueTemplate);
  device=(deviceName && *deviceName)?_getOrCreateDeviceForDriver(xo, epDriver, deviceName):NULL;
  
  DBG_ERROR(AQH_LOGDOMAIN,
	    "Creating value: service=\"%s\", device=\"%s\", value \"%s\"",
	    serviceName?serviceName:"<no service>", deviceName?deviceName:"<no device>", valueName?valueName:"<no value>");
  v=AQH_Value_new();
  AQH_Value_SetDriver(v, serviceName);
  AQH_Value_SetName(v, AQH_Value_GetName(valueTemplate));
  AQH_Value_SetNameForSystem(v, valueNameForSystem);
  AQH_Value_SetValueUnits(v, AQH_Value_GetValueUnits(valueTemplate));
  AQH_Value_SetValueType(v, AQH_Value_GetValueType(valueTemplate));
  AQH_Value_SetModality(v, AQH_Value_GetModality(valueTemplate));
  AQH_Value_SetTimestampCreation(v, (uint64_t) time(NULL));
  if (device) {
    AQH_Value_SetDeviceNameForSystem(v, AQH_Device_GetNameForSystem(device));
    AQH_Value_SetDeviceName(v, AQH_Device_GetName(device));
  }
  AQH_Storage_AddValue(xo->storage, v);
}



void _updateValue(AQHOME_SERVER *xo, AQH_VALUE *value, const char *deviceName, const AQH_VALUE *valueTemplate)
{
  int chg=0;
  const char *s1;
  const char *s2;
  int i1;
  int i2;

  DBG_INFO(AQH_LOGDOMAIN, "Updating value \"%s\"", deviceName);
  s1=AQH_Value_GetValueUnits(valueTemplate);
  s2=AQH_Value_GetValueUnits(value);
  if (s1 && *s1) {
    if (!(s2 && *s2) || (strcasecmp(s1, s2)!=0)) {
      AQH_Value_SetValueUnits(value, s1);
      chg=1;
    }
  }

  i1=AQH_Value_GetValueType(valueTemplate);
  i2=AQH_Value_GetValueType(value);
  if (i1!=AQH_ValueDataType_Unknown) {
    if (i1!=i2) {
      AQH_Value_SetValueType(value, i1);
      chg=1;
    }
  }

  i1=AQH_Value_GetModality(valueTemplate);
  i2=AQH_Value_GetModality(value);
  if (i1!=AQH_ValueModality_Unknown) {
    if (i1!=i2) {
      AQH_Value_SetModality(value, i1);
      chg=1;
    }
  }

  if (chg)
    AQH_Storage_AddRuntimeFlags(xo->storage, AQH_STORAGE_RTFLAGS_MODIFIED);
}



AQH_DEVICE *_getOrCreateDeviceForDriver(AQHOME_SERVER *xo, AQH_OBJECT *epDriver, const char *deviceName)
{
  const char *serviceName;
  AQH_DEVICE *device;
  GWEN_BUFFER *buf;

  serviceName=AQH_Endpoint_GetServiceName(epDriver);

  buf=GWEN_Buffer_new(0, 256, 0, 1);
  GWEN_Buffer_AppendArgs(buf, "%s/%s", (serviceName && *serviceName)?serviceName:"unknown", deviceName);

  device=AQH_Storage_GetDeviceByNameForSystem(xo->storage, GWEN_Buffer_GetStart(buf));
  if (device==NULL) {
    if (AQH_Endpoint_GetPermissions(epDriver) & AQH_ENDPOINT_PERMS_ADDDEVICE) {
      DBG_ERROR(AQH_LOGDOMAIN, "Creating device \"%s\"", GWEN_Buffer_GetStart(buf));
      device=AQH_Device_new();
      AQH_Device_SetDriver(device, serviceName);
      AQH_Device_SetName(device, deviceName);
      AQH_Device_SetNameForSystem(device, GWEN_Buffer_GetStart(buf));
      AQH_Device_SetTimestampCreation(device, (uint64_t) time(NULL));
      AQH_Storage_AddDevice(xo->storage, device);
    }
    else {
      DBG_ERROR(AQH_LOGDOMAIN, "No permissions to create device \"%s\"", GWEN_Buffer_GetStart(buf));
      GWEN_Buffer_free(buf);
      return NULL;
    }
  }
  GWEN_Buffer_free(buf);
  return device;
}




/* xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
 * helper functions
 * xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
 */

int _createPidFile(const char *pidFilename)
{
  FILE *f;
  int pidfd;

  if (remove(pidFilename)==0) {
    DBG_ERROR(0, "Old PID file existed, removed. (Unclean shutdown?)");
  }

#ifdef HAVE_SYS_STAT_H
  pidfd = open(pidFilename, O_EXCL|O_CREAT|O_WRONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
  if (pidfd < 0) {
    DBG_ERROR(NULL, "Could not create PID file \"%s\" (%s), aborting.", pidFilename, strerror(errno));
    return GWEN_ERROR_IO;
  }

  f = fdopen(pidfd, "w");
#else /* HAVE_STAT_H */
  f=fopen(pidFilename,"w+");
#endif /* HAVE_STAT_H */

  /* write pid */
#ifdef HAVE_GETPID
  fprintf(f,"%d\n",getpid());
#else
  fprintf(f,"-1\n");
#endif
  if (fclose(f)) {
    DBG_ERROR(0, "Could not close PID file \"%s\" (%s), aborting.", pidFilename, strerror(errno));
    return GWEN_ERROR_IO;
  }
  return 0;
}



int _readArgs(int argc, char **argv, GWEN_DB_NODE *dbArgs)
{
  int rv;
  const GWEN_ARGS args[]= {
    {
      GWEN_ARGS_FLAGS_HAS_ARGUMENT, /* flags */
      GWEN_ArgsType_Char,           /* type */
      "loglevel",                   /* name */
      0,                            /* minnum */
      1,                            /* maxnum */
      "L",                          /* short option */
      "loglevel",                   /* long option */
      I18S("Specify loglevel"),     /* short description */
      I18S("Specify loglevel")      /* long description */
    },
    {
      GWEN_ARGS_FLAGS_HAS_ARGUMENT, /* flags */
      GWEN_ArgsType_Char,           /* type */
      "tcpAddress",                 /* name */
      0,                            /* minnum */
      1,                            /* maxnum */
      "t",                          /* short option */
      "tcpaddress",                 /* long option */
      I18S("Specify the TCP address to listen on (disabled if missing)"),
      I18S("Specify the TCP address to listen on (disabled if missing)")
    },
    {
      GWEN_ARGS_FLAGS_HAS_ARGUMENT, /* flags */
      GWEN_ArgsType_Int,            /* type */
      "tcpPort",                    /* name */
      0,                            /* minnum */
      1,                            /* maxnum */
      "P",                          /* short option */
      "tcpport",                    /* long option */
      I18S("Specify the TCP port to listen on"),
      I18S("Specify the TCP port to listen on")
    },
    {
      GWEN_ARGS_FLAGS_HAS_ARGUMENT, /* flags */
      GWEN_ArgsType_Char,           /* type */
      "datafolder",                 /* name */
      0,                            /* minnum */
      1,                            /* maxnum */
      NULL,                         /* short option */
      "datafolder",                 /* long option */
      I18S("Folder where data files are stored"),
      I18S("Folder where data files are stored")
    },
    {
      GWEN_ARGS_FLAGS_HAS_ARGUMENT, /* flags */
      GWEN_ArgsType_Char,           /* type */
      "pidfile",                    /* name */
      0,                            /* minnum */
      1,                            /* maxnum */
      "p",                          /* short option */
      "pidfile",                    /* long option */
      I18S("Specify the PID file"),
      I18S("Specify the PID file")
    },
    {
      GWEN_ARGS_FLAGS_HAS_ARGUMENT, /* flags */
      GWEN_ArgsType_Int,            /* type */
      "timeout",                    /* name */
      0,                            /* minnum */
      1,                            /* maxnum */
      "T",                          /* short option */
      "timeout",                     /* long option */
      I18S("Specify timeout in second (default: no timeout)"),
      I18S("Specify timeout in second (default: no timeout)")
    },
    {
      GWEN_ARGS_FLAGS_HELP | GWEN_ARGS_FLAGS_LAST, /* flags */
      GWEN_ArgsType_Int,            /* type */
      "help",                       /* name */
      0,                            /* minnum */
      0,                            /* maxnum */
      "h",                          /* short option */
      "help",
      I18S("Show this help screen."),
      I18S("Show this help screen.")
    }
  };

  rv=GWEN_Args_Check(argc, argv, 1, 0, args, dbArgs);
  if (rv==GWEN_ARGS_RESULT_ERROR) {
    fprintf(stderr, "ERROR: Could not parse arguments main\n");
    return GWEN_ERROR_INVALID;
  }
  else if (rv==GWEN_ARGS_RESULT_HELP) {
    GWEN_BUFFER *ubuf;

    ubuf=GWEN_Buffer_new(0, 1024, 0, 1);
    GWEN_Buffer_AppendArgs(ubuf,
                           I18N("This is version %s.\nUsage: %s [OPTIONS]\n\nOptions:\n"),
                           AQHOME_VERSION_STRING,
                           argv[0]);
    if (GWEN_Args_Usage(args, ubuf, GWEN_ArgsOutType_Txt)) {
      fprintf(stderr, "ERROR: Could not create help string\n");
      return 1;
    }
    GWEN_Buffer_AppendString(ubuf, "\n");

    fprintf(stdout, "%s\n", GWEN_Buffer_GetStart(ubuf));
    GWEN_Buffer_free(ubuf);
    return GWEN_ERROR_CLOSE;
  }
  return 0;
}




