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

struct si_write_data {
	char	* d_object;
	char	* d_attr;
	char	* d_value;
};

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

static int write_init(struct si_action * a)
{
	struct si_write_data * data;
	int error = 0;

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

	data = calloc(1, sizeof(struct si_write_data));
	if (data) {
		data->d_object = a->a_argv[0];
		data->d_attr = a->a_argv[1];
		data->d_value = a->a_argv[2];
		a->a_data = data;
	} else
		error = -ENOMEM;
	return error;
}

static int write_exec(struct si_action * a)
{
	struct si_write_data * data = a->a_data;
	struct sysfs_object so;
	int error;
	int len;

	dbg("Object: %s, Attribute: %s, Value: %s\n",
	    data->d_object, data->d_attr, data->d_value);

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

	len = strlen(data->d_value);
	error = sysfs_write_file(data->d_attr, data->d_value, len);
	if (error == len)
		error = 0;
	else if (error > 0)
		error = -EFAULT;
	sysfs_object_exit(&so);
	return error;
}

static void write_exit(struct si_action * a)
{
	struct si_write_data * data = a->a_data;

	a->a_data = NULL;
	free(data);
}

static const char * write_help = "Write an attribute.";
static const char * write_usage = "<object> <attribute> <value>";

decl_cmd(write);

