#include "mologram/tapi/SecretHistoryStore.hpp"
#include <cerrno>
#include <cstring>
#include <fcntl.h>
#include <filesystem>
#include <fstream>
#include <iterator>
#include <unistd.h>
#include "mologram/Sha256.hpp"
namespace mologram {
namespace fs = std::filesystem;
static bool writeFile(const std::string& path, const std::string& bytes, std::string& err) {
int fd = ::open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);
if (fd < 0) { err = std::string("open: ") + std::strerror(errno); return false; }
size_t off = 0;
while (off < bytes.size()) {
ssize_t n = ::write(fd, bytes.data() + off, bytes.size() - off);
if (n < 0) { if (errno == EINTR) continue; err = std::string("write: ") + std::strerror(errno); ::close(fd); return false; }
off += (size_t)n;
}
if (::fsync(fd) != 0) { err = std::string("fsync: ") + std::strerror(errno); ::close(fd); return false; }
::close(fd);
return true;
}
SecretHistoryStore::Log SecretHistoryStore::load() {
Log log;
if (!enabled()) return log;
std::error_code ec;
if (!fs::exists(path_, ec)) return log;
std::ifstream in(path_, std::ios::binary);
if (!in) { rejected_++; return log; }
std::string all((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
size_t nl = all.find('\n'); // the first line is the SHA-256 of the JSON that follows: one file, one atomic rename
if (nl == std::string::npos) { rejected_++; return log; }
std::string want = all.substr(0, nl), bytes = all.substr(nl + 1);
if (Sha256::hexOf(bytes) != want) { rejected_++; return log; }
auto v = ttgui::json::parse(bytes);
if (!v || !v->isObj()) { rejected_++; return log; }
const js::Value* chats = v->find("chats");
if (!chats || !chats->isObj()) { rejected_++; return log; }
for (const auto& kv : *chats->asObj()) {
const js::Array* a = kv.second.asArr();
if (!a) continue;
int id = 0;
try { id = std::stoi(kv.first); } catch (...) { continue; }
log[id] = *a;
}
return log;
}
bool SecretHistoryStore::save(const Log& log, std::string& err) {
if (!enabled()) return true;
js::Object chats;
for (const auto& kv : log) chats[std::to_string(kv.first)] = js::Value(js::Array(kv.second));
js::Object root;
root["v"] = js::Value(1);
root["chats"] = js::Value(std::move(chats));
std::string bytes = ttgui::json::dump(js::Value(std::move(root)));
std::error_code ec;
fs::path dir = fs::path(path_).parent_path();
if (!dir.empty()) fs::create_directories(dir, ec);
std::string tmp = path_ + ".tmp";
if (!writeFile(tmp, Sha256::hexOf(bytes) + "\n" + bytes, err)) {
fs::remove(tmp, ec);
return false;
}
fs::rename(tmp, path_, ec);
if (ec) { err = "rename: " + ec.message(); return false; }
return true;
}
} // namespace mologram