#include "external"

unsigned  External::target(struct in_addr clientip,
		     BackendVector &targetlist) {
    
    // Prepare command to run
    ostringstream o;
    o << config.externalalgorithm() << ' ' << balancer.nbackends();
    for (unsigned i = 0; i < balancer.nbackends(); i++)
	o << ' ' << balancer.backend(i).description() << ' '
	  << balancer.backend(i).availablestr()
	  << ' ' << balancer.backend(i).connections();
    msg("External algorithm: invoking '" << o.str() << '\n');

    FILE *f;
    if (! (f = popen (o.str().c_str(), "r")) )
	throw Error("Cannot start '" + o.str() + ": " + strerror(errno));
    unsigned i;
    if (fscanf (f, "%u", &i) < 1) {
	pclose(f);
	throw Error("External algorithm '" + o.str() +
		    "' did not reply with a number");
    }
    msg("External algorithm says: " << i << '\n');

    if (i >= balancer.nbackends()) {
	pclose(f);
	ostringstream o;
	o << "External algorithm '" << o.str() << "': answer "
	  << i << " out of bounds";
	throw Error(o.str());
    }
    if (pclose (f))
	throw Error("External algorithm '" + o.str() +
		    "' terminated with error");

    return (i);
}
