#pragma once

#include <util/network/init.h>
#include <util/generic/yexception.h>
#include <util/stream/output.h>

inline TString GetLocalFQDN() {
    static TString fqdn;

    if (!fqdn.empty()) {
        return fqdn;
    }

    struct addrinfo hints;
    struct addrinfo *ais;
    char buf[1024] = { 0 };

    if (gethostname(buf, sizeof(buf)) != 0) {
        ythrow yexception() << "can not get hostname";
    }

    memset(&hints, 0, sizeof(hints));

    hints.ai_flags = AI_CANONNAME;

    if (getaddrinfo(buf, nullptr, &hints, &ais) != 0) {
        ythrow yexception() << "can not get local FQDN";
    }

    fqdn = ais->ai_canonname;
    fqdn.to_lower();

    freeaddrinfo(ais);
    return fqdn;
}
