#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <getopt.h>
#include <string.h>
#include "sysfs.h"
#include "si.h"

struct si_cat_data {
	char			* d_object;
	char			* d_attr;
	struct record_col	d_rc;
};

/**
 *	cat_init - Check arguments and allocate private data structures.
 *	@a:	Session data.
 */

static int cat_init(struct si_action * a)
{
	struct si_cat_data * data;
	int error = 0;

	if (a->a_argc != 2)
		return -EINVAL;

	data = calloc(1, sizeof(struct si_cat_data));
	if (!data)
		return -ENOMEM;

	data->d_object = a->a_argv[0];
	data->d_attr = a->a_argv[1];
	a->a_data = data;
	return error;
}


static int cat_exec(struct si_action * a)
{
	struct si_cat_data * data = a->a_data;
	struct sysfs_object so;
	char buffer[PAGE_SIZE];
	int error;

	error = sysfs_object_init(&so, data->d_object);
	if (error)
		return error;

	error = rc_init(&data->d_rc, 1);
	if (error)
		goto ObjectExit;

	error = sysfs_read_file(data->d_attr, buffer);
	if (error > 0)
		error = 0;
	else
		goto RcExit;

	error = record_add(&data->d_rc, buffer);
	if (error)
		goto RcExit;
	rc_add(a, &data->d_rc);

 ObjectExit:
	sysfs_object_exit(&so);
	return error;
 RcExit:
	rc_exit(&data->d_rc);
	goto ObjectExit;
}

static void cat_exit(struct si_action * a)
{
	struct si_cat_data * data = a->a_data;
	a->a_data = NULL;
	rc_exit(&data->d_rc);
	free(data);
}

static const char * cat_help = "Read a single attribute.";
static const char * cat_usage = "<object> <attribute>";

decl_cmd(cat);

