/*
 * service_helper.c: helper functions for managing services
 *
 * Copyright (C) 2023 IOPSYS Software Solutions AB. All rights reserved.
 *
 * See LICENSE file for license related information.
 */

#include <string.h>
#include <signal.h>
#include <time.h>
#include <stdbool.h>
#include <errno.h>
#include <libubox/blobmsg.h>
#include <libubus.h>
#include "common.h"
#include "event.h"
#include "libdmtree/dmentry.h"
#include "libdmtree/dmcommon.h"

#define SERVICE_RESTART_DELAY_SEC 10

static void timer_handler(union sigval sv)
{
	(void)sv;

	send_fw_rules_clear_event();

	dm_uci_init();
	bbf_entry_commit_services();
	dm_uci_exit();

	INFO("Restart services");

	dmcmd("/bin/systemctl", 2, "restart", "voicemngr");
#ifdef DM_ENABLE_DECT
	dmcmd("/bin/systemctl", 2, "restart", "dectmngr");
#endif
	dmcmd("/bin/systemctl", 2, "restart", "asterisk");
}

int restart_services()
{
	static timer_t timerid;
	static bool init;
	struct sigevent sev;
	struct itimerspec trigger;

	if (!init) {
		memset(&sev, 0, sizeof(struct sigevent));
		sev.sigev_notify = SIGEV_THREAD;
		sev.sigev_notify_function = &timer_handler;

		if (timer_create(CLOCK_MONOTONIC, &sev, &timerid) != 0) {
			ERR("Failed to create timer, err: %s (%d)", strerror(errno), errno);
			return -1;
		}

		init = true;
	}

	// delay restart to accumulate all changes
	memset(&trigger, 0, sizeof(struct itimerspec));
	trigger.it_value.tv_sec = SERVICE_RESTART_DELAY_SEC;
	if (timer_settime(timerid, 0, &trigger, NULL) != 0) {
		ERR("Failed to set timer, err: %s (%d)", strerror(errno), errno);
		return -1;
	}

	return 0;
}
