/*
 * swmod_host.c: SWMOD deamon
 *
 * Copyright (C) 2020-2023 IOPSYS Software Solutions AB. All rights reserved.
 *
 * Author: Amin Ben Ramdhane <amin.benramdhane@pivasoftware.com>
 *
 * See LICENSE file for license related information.
 */

#include <stdio.h>
#include <stdbool.h>
#include <sys/sysinfo.h>
#include <sys/utsname.h>
#include <sys/statvfs.h>

#include "tools.h"
#include "swmod_uci.h"
#include "swmod_host.h"
#include "swmod.h"

void get_host_system_info(ExecEnv_t *host_ee, const char *bundle_root)
{
	if (host_ee == NULL)
		return;

	swmod_strncpy(host_ee->type, "Virtual_EE", MAX_LEN_64);

	struct sysinfo sinfo;

	if (sysinfo(&sinfo) == 0) {
		host_ee->allocated_memory = (sinfo.totalram / 1024);
		host_ee->available_memory = (sinfo.freeram / 1024);
	}

	struct statvfs dinfo;
	if (statvfs(bundle_root, &dinfo) == 0) {
		host_ee->allocated_disk_space = (dinfo.f_bsize * dinfo.f_blocks) / 1024;
		host_ee->available_disk_space = (dinfo.f_bsize * dinfo.f_bfree) / 1024;
	} else {
		host_ee->allocated_disk_space = 0;
		host_ee->available_disk_space = 0;
	}
}

void populate_host_system_environment(struct list_head *ee_head, const char *bundle_root)
{
	ExecEnv_t host_ee;
	memset(&host_ee, 0, sizeof(ExecEnv_t));

	host_ee.exists = true;
	host_ee.pause = 0;
	host_ee.ee_type = EE_TYPE_HOST;
	host_ee.autoboot = 1;
	host_ee.eeid = PARENT_EEID;
	host_ee.parent_eeid = 0;

	char *tmp = strrchr(bundle_root, '/');
	if (tmp) {
		swmod_strncpy(host_ee.name, tmp+1, MAX_LEN_32);
	}

	swmod_strncpy(host_ee.status, "Up", MAX_LEN_32);

	swmod_add_ee_in_list(ee_head, &host_ee);
}
