/*
 * libsysactivity
 * http://sourceforge.net/projects/libsysactivity/
 * Copyright (c) 2009-2011 Carlos Olmedo Escobar <carlos.olmedo.e@gmail.com>
 *               2002 James C. Warner <warnerjc@worldnet.att.net>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <errno.h>

#include "utils.h"

typedef struct {
	uint64_t u, n, s, i, w, x, y, z; // as represented in /proc/stat
} CPU_STATES_t;

typedef struct CPU_t {
	CPU_STATES_t diff, saved;
	unsigned id; // the CPU ID number
} CPU_t;

static void parse_line(CPU_STATES_t* __restrict__ states, char* __restrict__ pos) SA_NONNULL;
static void calculate_cpu(struct sa_cpu* __restrict__ dst, CPU_t* __restrict__ cpu, const CPU_STATES_t* __restrict__ new_states) SA_NONNULL;

extern int kernel_version;
__thread long int number_cpus;
__thread FILE* fp;
__thread CPU_t* cpus;
__thread char buf[320];

int sa_open_cpu() {
	fp = NULL;
	cpus = NULL;

	if (kernel_version < 24)
		return ENOTSUP;

	number_cpus = sysconf(_SC_NPROCESSORS_ONLN);
	if (number_cpus < 0)
		return ENOSYS;

	fp = fopen("/proc/stat", "r");
	if (fp == NULL)
		return EIO;

	return 0;
}

int sa_close_cpu() {
	if (fp != NULL)
		fclose(fp);
	if (cpus != NULL)
		free(cpus);

	return 0;
}

int sa_reset_cpus() {
	fclose(fp);
	fp = fopen("/proc/stat", "r");
	if (fp == NULL)
		return EIO;
	if (fgets(buf, sizeof buf, fp) == NULL)
		return EIO;

	long int new_number_cpus = sysconf(_SC_NPROCESSORS_ONLN);
	if (new_number_cpus < 0)
		return ENOSYS;
	if (cpus == NULL || number_cpus != new_number_cpus) {
		number_cpus = new_number_cpus;
		CPU_t* temp_cpus;
		temp_cpus = realloc(cpus, number_cpus * sizeof(CPU_t));
		if (temp_cpus == NULL)
			return ENOMEM;
		cpus = temp_cpus;
	}

	return 0;
}

int sa_count_cpus(uint16_t* number) {
	if (number == NULL)
		return EINVAL;

	*number = (uint16_t) number_cpus;
	return 0;
}

int sa_get_cpu(uint16_t index, struct sa_cpu* dst) {
	if (index >= number_cpus || dst == NULL)
		return EINVAL;

	uint16_t i;
	CPU_STATES_t new_states;
	for (i = 0; i < number_cpus; ++i) {
		if (fgets(buf, sizeof buf, fp) == NULL)
			return EIO;

		if (index != i)
			continue;

		cpus[i].id = i;
		errno = 0;
		parse_line(&new_states, buf);
		if (errno != 0)
			return ENODEV;

		calculate_cpu(dst, &cpus[i], &new_states);
		return 0;
	}

	return ENODEV;
}

int sa_get_cpus(struct sa_cpu* dst, uint16_t dst_size, uint16_t* written) {
	if (dst == NULL || dst_size == 0 || written == NULL)
		return EINVAL;

	*written = 0;
	uint16_t i;
	CPU_STATES_t new_states;
	for (i = 0; i < number_cpus; ++i) {
		if (fgets(buf, sizeof buf, fp) == NULL)
			return EIO;

		if (i >= dst_size)
			return ENOMEM;

		cpus[i].id = i;
		errno = 0;
		parse_line(&new_states, buf);
		if (errno != 0)
			return ENODEV;

		calculate_cpu(&dst[i], &cpus[i], &new_states);
		++(*written);
	}

	return 0;
}

static void parse_line(CPU_STATES_t* __restrict__ states, char* __restrict__ pos) {
	pos = skip_value(pos);
	states->u = strtoull(pos, NULL, 10);
	pos = skip_value(pos);
	states->n = strtoull(pos, NULL, 10);
	pos = skip_value(pos);
	states->s = strtoull(pos, NULL, 10);
	pos = skip_value(pos);
	states->i = strtoull(pos, NULL, 10);
	pos = skip_value(pos);
	states->w = strtoull(pos, NULL, 10);
	pos = skip_value(pos);
	states->x = strtoull(pos, NULL, 10);
	pos = skip_value(pos);
	states->y = strtoull(pos, NULL, 10);
	pos = skip_value(pos);
	states->z = strtoull(pos, NULL, 10);
}

static void calculate_cpu(struct sa_cpu* __restrict__ dst, CPU_t* __restrict__ cpu, const CPU_STATES_t* __restrict__ new_states) {
	cpu->diff.u = new_states->u - cpu->saved.u;
	cpu->diff.s = new_states->s - cpu->saved.s;
	cpu->diff.n = new_states->n - cpu->saved.n;
	cpu->diff.i = new_states->i - cpu->saved.i;
	cpu->diff.w = new_states->w - cpu->saved.w;
	cpu->diff.x = new_states->x - cpu->saved.x;
	cpu->diff.y = new_states->y - cpu->saved.y;
	cpu->diff.z = new_states->z - cpu->saved.z;

	uint64_t total = cpu->diff.u + cpu->diff.s + cpu->diff.n + cpu->diff.i + cpu->diff.w
			+ cpu->diff.x + cpu->diff.y + cpu->diff.z;
	float scale;
	if (total == 0)
		scale = 1;
	else
		scale = (float) total / 100.0;

	dst->id = cpu->id;
	dst->user = cpu->diff.u / scale;
	dst->nice = cpu->diff.n / scale;
	dst->system = cpu->diff.s / scale;
	dst->idle = cpu->diff.i / scale;
	dst->waiting_for_io = cpu->diff.w / scale;
	dst->hardware_irq = cpu->diff.x / scale;
	dst->software_irq = cpu->diff.y / scale;
	dst->stolen = cpu->diff.z / scale;

	cpu->saved = *new_states;
}
