/*
 * Created by jiaqiang.ye@lnxall.com
 *
 * OPC UA Server for x86 gateway
 *
 * 2022/01/04
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <signal.h>

#include <open62541.h>

#include "opcua_lnxall.h"

/* global loop flag variable */
static volatile UA_Boolean g_running;

/* signal handler function */
static void signal_int_handler(int signo)
{
    g_running = false;
    fprintf(stderr, "Warning, recevied signal: %d\n", signo);
    fflush(stderr);
}

int main(int argc, char *argv[])
{
    UA_StatusCode rval;
    UA_Server * server = NULL;
    oulnx_server_t * opcsvr = NULL;
    UA_ServerConfig * config = NULL;
    const char * cfgdir = NULL;

    /* set loop-flag to true */
    g_running = true;

    rval = UA_STATUSCODE_BADINTERNALERROR;
    /* register signal handler */
    if (signal(SIGINT, signal_int_handler) == SIG_ERR ||
        signal(SIGTERM, signal_int_handler) == SIG_ERR) {
        fputs("Error, failed to register signal handler!\n", stderr);
        fflush(stderr);
        exit(1);
    }

    /* create OPC UA server and configure it */
    server = UA_Server_new();
    if (argc > 1) {
        cfgdir = argv[1];
        fprintf(stdout, "Using configure directory: %s\n", cfgdir);
        fflush(stdout);
    }

    opcsvr = oulnx_server_init(server);
    if (opcsvr == NULL)
        goto err0;

    config = UA_Server_getConfig(server);
    UA_ServerConfig_setDefault(config);

    if (oulnx_server_load(opcsvr, cfgdir, config) < 0)
        goto err0;

    rval = UA_Server_run(server, &g_running);

err0:
    if (opcsvr != NULL)
        oulnx_server_free(opcsvr);
    if (server != NULL) {
        UA_Server_delete(server);
        server = NULL;
    }
    return rval == UA_STATUSCODE_GOOD ? EXIT_SUCCESS : EXIT_FAILURE;
}
