#include "torlinkc/engine/bootguard.hpp"

#include <chrono>
#include <filesystem>
#include <fstream>
#include <unistd.h>

#include <nlohmann/json.hpp>

#include "torlinkc/config/paths.hpp"

namespace fs = std::filesystem;

namespace torlinkc {

bool wasBootInterrupted() {
  std::error_code ec;
  return fs::exists(paths::bootMarkerFile(), ec);
}

void armBootMarker() {
  try {
    fs::create_directories(fs::path(paths::bootMarkerFile()).parent_path());
    auto now = std::chrono::duration_cast<std::chrono::milliseconds>(
                   std::chrono::system_clock::now().time_since_epoch())
                   .count();
    nlohmann::json j;
    j["at"] = now;
    j["pid"] = static_cast<int>(getpid());
    std::ofstream out(paths::bootMarkerFile(), std::ios::binary | std::ios::trunc);
    out << j.dump();
  } catch (...) {
    // Failing to write the marker never blocks a boot.
  }
}

void disarmBootMarker() {
  std::error_code ec;
  fs::remove(paths::bootMarkerFile(), ec);
}

}  // namespace torlinkc
