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

struct si_cls_data {
	char	* d_cls;
	struct record_col	d_rc;
};

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

static int cls_init(struct si_action * a)
{
	struct si_cls_data * data;
	int error = 0;

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

	/*
	 * First argument will be the class.
	 *
	 * Anything else is uncivilized and invalid.
	 */
	if (a->a_argc == 1)
		data->d_cls = a->a_argv[0];
	else if (a->a_argc)
		error = -EINVAL;

	if (!error)
		a->a_data = data;
	return error;
}

static int record_classes(struct si_action * a)
{
	struct si_cls_data * data = a->a_data;
	struct sysfs_object so;
	int error;

	error = sysfs_object_init(&so, "class");
	if (error)
		return error;

	error = record_children(a, &data->d_rc);

	if (!error) {
		data->d_rc.rc_name = "Class";
		data->d_rc.rc_suf = "es";
	}
	sysfs_object_exit(&so);
	return error;
}

static int record_one_class(struct si_action * a)
{
	struct si_cls_data * data = a->a_data;
	struct sysfs_object so;
	char class_path[PATH_MAX];
	int error;
	int len;
	
	len = snprintf(class_path, PATH_MAX, "class/%s", data->d_cls);
	if (len > PATH_MAX)
		return -EOVERFLOW;

	error = sysfs_object_init(&so, class_path);
	if (error)
		return error;

	error = record_children(a, &data->d_rc);
	if (!error) {
		data->d_rc.rc_name = "Class Device";
		data->d_rc.rc_suf = "s";
	}

	sysfs_object_exit(&so);
	return error;
}


static int cls_exec(struct si_action * a)
{
	struct si_cls_data * data = a->a_data;
	int error = 0;

	/*
	 * If we don't have a class specified, list all the classes.
	 * Otherwise, we list all the class devices.
	 */
	if (!data->d_cls) {
		error = record_classes(a);
	} else {
		error = record_one_class(a);
	}

	if (!error)
		rc_add(a, &data->d_rc);

	return error;
}

static void cls_exit(struct si_action * a)
{
	struct si_cls_data * data = a->a_data;

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

static const char * cls_help = "Template Help";
static const char * cls_usage = "[<device class>]";

decl_cmd(cls);

