#include "status.h"

#include <util/stream/file.h>
#include <util/string/strip.h>
#include <util/string/subst.h>

inline bool IsBitMask(const TString& s) {
    return s.Contains("Cap") || s.Contains("Sig") || s.Contains("Shd");
}

NJson::TJsonValue GetProcStatus() {
    NJson::TJsonValue json;
    TUnbufferedFileInput fi("/proc/self/status");
    TString line;
    while (fi.ReadLine(line)) {
        size_t pos = line.find(':');
        if (pos != TString::npos) {
            TString left = line.substr(0, pos);
            TString right = Strip(line.substr(pos + 1));
            if (!left.empty() && !right.empty()) {
                ui64 num;
                pos = right.find(" kB");
                if (pos != TString::npos) {
                    right = right.substr(0, pos);
                    TryFromString(right, num);
                    json.InsertValue(left, num * 1024);
                } else if (!IsBitMask(left) &&
                           TryFromString(right, num)) {
                    json.InsertValue(left, num);
                } else {
                    SubstGlobal(right, '\t', ' ');
                    json.InsertValue(left, right);
                }
            }
        }
    }
    return json;
}
