/** Node-type for subprocess node-types.
 *
 * @author Steffen Vogel <stvogel@eonerc.rwth-aachen.de>
 * @copyright 2014-2019, Institute for Automation of Complex Power Systems, EONERC
 * @license GNU General Public License (version 3)
 *
 * VILLASnode
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *********************************************************************************/

#include <string>

#include <villas/node.h>
#include <villas/plugin.h>
#include <villas/node/config.h>
#include <villas/nodes/exec.hpp>

using namespace villas::utils;

int exec_parse(struct node *n, json_t *cfg)
{
	struct exec *e = (struct exec *) n->_vd;

	json_error_t err;
	int ret, flush = 0;

	const char *command;
	const char *format = "villas.human";

	ret = json_unpack_ex(cfg, &err, 0, "{ s: s, s?: s, s?: b }",
		"exec", &command,
		"format", &format,
		"flush", &flush
	);
	if (ret)
		jerror(&err, "Failed to parse configuration of node %s", node_name(n));

	e->command = command;
	e->flush = flush;

	e->format = format_type_lookup(format);
	if (!e->format)
		error("Invalid format '%s' for node %s", format, node_name(n));

	if (!(e->format->flags & IO_NEWLINES))
		error("The exec node-type currently supports only line-delimited formats");

	return 0;
}

int exec_prepare(struct node *n)
{
	int ret;
	struct exec *e = (struct exec *) n->_vd;

	/* Initialize IO */
	ret = io_init(&e->io, e->format, &n->in.signals, SAMPLE_HAS_ALL);
	if (ret)
		return ret;

	ret = io_check(&e->io);
	if (ret)
		return ret;

	return 0;
}

int exec_destroy(struct node *n)
{
	int ret;
	struct exec *e = (struct exec *) n->_vd;

	ret = io_destroy(&e->io);
	if (ret)
		return ret;

	return 0;
}

int exec_start(struct node *n)
{
	struct exec *e = (struct exec *) n->_vd;

	/* Start subprocess */
	e->proc = std::make_unique<Popen>(e->command);
	debug(2, "Started sub-process with pid=%d", e->proc->getPid());

	return 0;
}

int exec_stop(struct node *n)
{
	struct exec *e = (struct exec *) n->_vd;

	/* Stop subprocess */
	debug(2, "Killing sub-process with pid=%d", e->proc->getPid());
	e->proc->kill(SIGINT);

	debug(2, "Waiting for sub-process with pid=%d to terminate", e->proc->getPid());
	e->proc->close();

	/** @todo: Check exit code of subprocess? */
	return 0;
}

int exec_read(struct node *n, struct sample *smps[], unsigned cnt, unsigned *release)
{
	struct exec *e = (struct exec *) n->_vd;

	size_t rbytes;
	int avail;
	std::string line;

	std::getline(e->proc->cin(), line);

	avail = io_sscan(&e->io, line.c_str(), line.length(), &rbytes, smps, cnt);
	if (rbytes - 1 != line.length())
		return -1;

	return avail;
}

int exec_write(struct node *n, struct sample *smps[], unsigned cnt, unsigned *release)
{
	struct exec *e = (struct exec *) n->_vd;

	size_t wbytes;
	int ret;
	char *line = new char[1024];

	ret = io_sprint(&e->io, line, 1024, &wbytes, smps, cnt);
	if (ret < 0)
		return ret;

	e->proc->cout() << line;

	if (e->flush)
		e->proc->cout().flush();

	delete line;

	return cnt;
}

char * exec_print(struct node *n)
{
	struct exec *e = (struct exec *) n->_vd;
	char *buf = nullptr;

	strcatf(&buf, "format=%s, exec=%s, flush=%s",
		format_type_name(e->format),
		e->command.c_str(),
		e->flush ? "yes" : "no"
	);

	return buf;
}

int exec_poll_fds(struct node *n, int fds[])
{
	struct exec *e = (struct exec *) n->_vd;

	fds[0] = e->proc->getFd();

	return 1;
}

static struct plugin p;

__attribute__((constructor(110)))
static void register_plugin() {
	if (plugins.state == STATE_DESTROYED)
		vlist_init(&plugins);

	p.name			= "exec";
	p.description		= "run subprocesses with stdin/stdout communication";
	p.type			= PLUGIN_TYPE_NODE;
	p.node.instances.state	= STATE_DESTROYED;
	p.node.vectorize	= 0;
	p.node.size		= sizeof(struct exec);
	p.node.parse		= exec_parse;
	p.node.print		= exec_print;
	p.node.prepare		= exec_prepare;
	p.node.destroy		= exec_destroy;
	p.node.start		= exec_start;
	p.node.stop		= exec_stop;
	p.node.read		= exec_read;
	p.node.write		= exec_write;
	p.node.poll_fds		= exec_poll_fds;

	vlist_init(&p.node.instances);
	vlist_push(&plugins, &p);
}

__attribute__((destructor(110)))
static void deregister_plugin() {
	if (plugins.state != STATE_DESTROYED)
		vlist_remove_all(&plugins, &p);
}