#include "backendcheck"

static int parse_port(string const &s) {
    int ret;
    if (sscanf(s.c_str(), "%d", &ret) < 1)
	ret = 0;
    return ret;
}

static string parse_uri(string const &s) {
    size_t slash = s.find_first_of('/');
    if (slash == string::npos)
	return ("/");
    return s.substr(slash);
}

void BackendCheck::parse(string setting) {
    // Resets to default
    if (!setting.size()) {
	check_type = c_connect;
	srv = "";
	prt = 0;
	geturi = "";
	extprog = "";
	return;
    }

    vector<string> parts = str2parts(setting, ':');

    // connect:IP:PORT
    if (parts.size() == 3 && parts[0] == "connect") {
	check_type = c_connect;
	srv = parts[1];
	prt = parse_port(parts[2]);
	geturi = "";
	extprog = "";
	return;
    }

    // get:IP:PORT
    // get:IP:PORT/URI
    if (parts.size() == 3 && parts[0] == "get") {
	check_type = c_get;
	srv = parts[1];
	prt = parse_port(parts[2]);
	geturi = parse_uri(parts[2]);
	extprog = "";
	return;
    }

    // external:PROGRAM
    if (parts.size() == 2 && parts[0] == "external") {
	check_type = c_external;
	srv = "";
	prt = 0;
	geturi = "";
	extprog = parts[1];
	return;
    }

    // No luck today
    throw Error("Back end check specifiers must be either an empty string, "
		"or 'connect:IP:PORT' or 'get:IP:PORT' or 'get'IP:PORT/URI' "
		"or 'external:PROGRAM'");
}
