/*
 * get_helper.c: Get Fast handler for bbfdmd
 *
 * Copyright (C) 2019-2023 IOPSYS Software Solutions AB. All rights reserved.
 *
 * Author: Vivek Dutta <vivek.dutta@iopsys.eu>
 * Author: Iryna Antsyferova <iryna.antsyferova@iopsys.eu>
 *
 * See LICENSE file for license related information.
 */

#define _XOPEN_SOURCE
#define _DEFAULT_SOURCE

#include <time.h>
#include <setjmp.h>

#include "get_helper.h"
#include "common.h"

#include "libdmtree/dmentry.h"


DMOBJ *DEAMON_DM_ROOT_OBJ = NULL;

// uloop.h does not have versions, below line is to use
// deprecated uloop_timeout_remaining for the time being
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"

static jmp_buf gs_jump_location;
static bool gs_jump_called_by_bbf = false;

void handle_pending_signal(int sig)
{
	if (gs_jump_called_by_bbf) {
		siglongjmp(gs_jump_location, 1);
	}

	ERR("Exception [%d] not cause by bbf dm, exit with error", sig);
	exit(1);
}

int bbfdm_cmd_exec(struct dmctx *bbf_ctx, int cmd)
{
	int fault = 0;

	if (bbf_ctx->in_param == NULL)
		return USP_FAULT_INTERNAL_ERROR;

	if (sigsetjmp(gs_jump_location, 1) == 0) {
		gs_jump_called_by_bbf = true;
		fault = bbf_entry_method(bbf_ctx, cmd);
	} else {
		ERR("PID [%ld]::Exception on [%d => %s]", getpid(), cmd, bbf_ctx->in_param);
		fault = USP_FAULT_INTERNAL_ERROR;
	}

	gs_jump_called_by_bbf = false;

	if (fault)
		WARNING("Fault [%d => %d => %s]", fault, cmd, bbf_ctx->in_param);

	return fault;
}

void bbf_init(struct dmctx *dm_ctx)
{
	bbf_ctx_init(dm_ctx, DEAMON_DM_ROOT_OBJ);
}

void bbf_cleanup(struct dmctx *dm_ctx)
{
	bbf_ctx_clean(dm_ctx);
}

void bbf_sub_init(struct dmctx *dm_ctx)
{
	bbf_ctx_init_sub(dm_ctx, DEAMON_DM_ROOT_OBJ);
}

void bbf_sub_cleanup(struct dmctx *dm_ctx)
{
	bbf_ctx_clean_sub(dm_ctx);
}

void bbf_commit()
{
	bbf_entry_restart_services(NULL, true);
}

