// Reference only. This is not injected into an existing CS 1.6 client.
// Build on a machine with libcurl: g++ client.cpp -lcurl -o tb-list
// It downloads the boosted server list and prints a console connect command.

#include <curl/curl.h>
#include <iostream>
#include <string>

static size_t write_cb(void* contents, size_t size, size_t nmemb, void* userp) {
    std::string* out = static_cast<std::string*>(userp);
    out->append(static_cast<char*>(contents), size * nmemb);
    return size * nmemb;
}

static std::string field(const std::string& object, const std::string& key) {
    std::string needle = "\"" + key + "\"";
    std::size_t pos = object.find(needle);
    if (pos == std::string::npos) return "";
    pos = object.find(':', pos);
    if (pos == std::string::npos) return "";
    pos = object.find_first_not_of(" \t\r\n", pos + 1);
    if (pos == std::string::npos) return "";
    if (object[pos] == '"') {
        std::size_t end = object.find('"', pos + 1);
        if (end == std::string::npos) return "";
        return object.substr(pos + 1, end - pos - 1);
    }
    std::size_t end = object.find_first_of(",}\r\n", pos);
    return object.substr(pos, end - pos);
}

int main() {
    CURL* curl = curl_easy_init();
    if (!curl) {
        std::cerr << "Could not start HTTP.\n";
        return 1;
    }
    std::string body;
    curl_easy_setopt(curl, CURLOPT_URL, "https://tb-team.com/boost/api/v1/servers.php");
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_cb);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &body);
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, 15L);
    CURLcode code = curl_easy_perform(curl);
    curl_easy_cleanup(curl);
    if (code != CURLE_OK) {
        std::cerr << "API request failed.\n";
        return 1;
    }
    if (body.find("\"servers\"") == std::string::npos) {
        std::cerr << "The API did not return a server list.\n";
        return 1;
    }
    std::size_t pos = 0;
    int shown = 0;
    while ((pos = body.find("\"ip\"", pos)) != std::string::npos) {
        std::size_t start = body.rfind('{', pos);
        std::size_t end = body.find('}', pos);
        if (start == std::string::npos || end == std::string::npos) break;
        std::string object = body.substr(start, end - start + 1);
        std::string name = field(object, "name");
        std::string ip = field(object, "ip");
        std::string port = field(object, "port");
        if (!ip.empty() && !port.empty()) {
            std::cout << name << "\nconnect " << ip << ":" << port << "\n";
            shown++;
        }
        pos = end + 1;
    }
    if (!shown) std::cout << "No boosted servers.\n";
    return 0;
}
