/*
 * Tester that delegates testing to an external script
 *
 * Copyright (C) 2003--2010  Enrico Zini <enrico@debian.org>
 *
 * 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 2 of the License, or
 * (at your option) 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, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include "scanner/script.h"
#include "scanner/scan.h"
#include "util/processrunner.h"
#include "util/output.h"
#include "options.h"

#include <memory>

using namespace std;
using namespace wibble::sys;

namespace scanner {

/*
 * Script test
 *
 * Runs program and succeeds if exit status is zero
 */
class ScriptScan : public Scan, public ProcessListener
{
protected:
	std::string _cmdline;

public:
	ScriptScan(const std::string& name, const std::string& cmdline)
		: Scan(name), _cmdline(cmdline) {}

	std::string signature() const
	{
		return "command '" + _cmdline + "'";
	}

	void handleTermination(const std::string& signature, int status)
	{
		verbose("script [%s] terminated with status %d\n", signature.c_str(), status);

		if (status != 0)
			return;

		success();
	}
};



Scan* Script::createScan(const std::string& name, const std::string& cmdline)
{
	auto_ptr<ScriptScan> res(new ScriptScan(name, cmdline));

	verbose("adding candidate script [%s] with tag [%s]\n", cmdline.c_str(), res->signature().c_str());
	vector<string> env;
	env.push_back("NAME=" + res->signature());
	env.push_back("IFACE=" + options.iface);
	env.push_back("GUESSNET=true");
	env.push_back(string("PATH=") + SCRIPTDIR + ":/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin");
	ProcessRunner::get().addProcess(res->signature(), cmdline, env, res.get());

	return res.release();
}

}

// vim:set ts=4 sw=4:
