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

static struct record_col rc_subsys;

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

static int subsys_init(struct si_action * a)
{
	int error = 0;

	if (a->a_argc > 1)
		error = -EINVAL;
	else if (a->a_argc) {
		a->a_data = strdup(a->a_argv[0]);
		if (!a->a_data)
			error = -ENOMEM;
	}
	return error;
}

static int record_one(struct si_action * a)
{
	char * subsys = a->a_data;
	struct sysfs_object so;
	int error;

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

	error = record_children(a, &rc_subsys);
	if (!error)
		rc_subsys.rc_name = subsys;
	sysfs_object_exit(&so);
	return error;
}

static int record_all(struct si_action * a)
{
	struct sysfs_object so;
	int error;

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

	error = record_children(a, &rc_subsys);
	if (!error) {
		rc_subsys.rc_name = "Subsystem";
		rc_subsys.rc_suf = "s";
	}
	sysfs_object_exit(&so);
	return error;
}

static int subsys_exec(struct si_action * a)
{
	int error;

	if (a->a_data)
		error = record_one(a);
	else
		error = record_all(a);
	return error;
}

static void subsys_exit(struct si_action * a)
{
	char * subsys = a->a_data;

	rc_exit(&rc_subsys);
	a->a_data = NULL;
	free(subsys);
}

static const char * subsys_help = "Show Configured Subsystems";
static const char * subsys_usage = "[<subsystem>]";

decl_cmd(subsys);

