// fork() and resurrect_after_fork
// Textbook section: Volume II, chapter 11, "Multithreading", section "fork".
// What it demonstrates: after fork() the child process continues to work with the same
//   environment; mdbx_env_resurrect_after_fork() restores the state of
//   locks/readers in the child.
// Build: g++ -std=c++17 -I<libmdbx-include> -I../common 15-fork-resurrect.c++ -lmdbx
// Run: ./15-fork-resurrect
// Expected output (POSIX):
//   parent: wrote key=v1
//   child: resurrected, reads key=v1, wrote key=child
//   parent: after child, key=child
//   ok: fork + resurrect_after_fork
// On Windows the example is not executed and reports a skip.
//
// SPDX-License-Identifier: Apache-2.0

#include <iostream>
#include <string>

#include "common.h++"
#include <mdbx.h++>

#if defined(_WIN32) || defined(_WIN64) || defined(_WINDOWS)
int main() {
  std::cout << "skipped: fork() is not available on Windows\n";
  return EXIT_SUCCESS;
}
#else
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int main() {
  try {
    const std::string path = std::string(example::tmpdir()) + "/mdbx-15-fork-resurrect.mdbx";
    mdbx::env::remove(path);
    mdbx::env_managed env = example::env_open(path);

    {
      auto txn = env.start_write();
      auto table = txn.open_map(nullptr);
      txn.insert(table, mdbx::slice("key"), mdbx::slice("v1"));
      txn.commit();
    }
    std::cout << "parent: wrote key=v1" << std::endl;
    // so that the stdout buffer is not duplicated in the child
    std::cout.flush();

    const pid_t pid = fork();
    if (pid < 0) {
      std::cerr << "fork failed\n";
      return EXIT_FAILURE;
    }

    if (pid == 0) {
      // The child: restore the environment after fork() and read the data.
      env.resurrect_after_fork();
      auto txn = env.start_write();
      auto table = txn.open_map(nullptr);
      std::cout << "child: resurrected, reads key=" << txn.get(table, mdbx::slice("key")).as_string() << std::endl;
      txn.upsert(table, mdbx::slice("key"), mdbx::slice("child"));
      txn.commit();
      env.close();
      _exit(EXIT_SUCCESS);
    }

    int status = 0;
    waitpid(pid, &status, 0);
    if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
      std::cerr << "child failed\n";
      return EXIT_FAILURE;
    }

    {
      auto txn = env.start_read();
      auto table = txn.open_map(nullptr);
      std::cout << "parent: after child, key=" << txn.get(table, mdbx::slice("key")).as_string() << "\n";
      txn.abort();
    }

    std::cout << "ok: fork + resurrect_after_fork\n";
    return EXIT_SUCCESS;
  } catch (const std::exception &ex) {
    std::cerr << "error: " << ex.what() << "\n";
    return EXIT_FAILURE;
  }
}
#endif // Windows vs POSIX