#include "client/linux/crash_generation/crash_generation_server.h"
#include "client/linux/handler/exception_handler.h"
#include "client/linux/handler/minidump_descriptor.h"

#include <sys/stat.h>
#include <sys/wait.h>

void OnClientDumpRequestCallback(void *context, const google_breakpad::ClientInfo *client_info, const string *file_path)
{
    printf("dump to: %s\n", file_path->c_str());
}

bool CrashCallback(const google_breakpad::MinidumpDescriptor &descriptor, void *context, bool succeeded)
{
    printf("dump to: %s\n", descriptor.path());
    return succeeded;
}
void crash()
{
    int *a = nullptr;
    *a = 1;
}

int main()
{
    int server_fd;
    int client_fd;
    std::string dump_path = ".";
    google_breakpad::CrashGenerationServer::CreateReportChannel(&server_fd, &client_fd);
    pid_t pid = fork();
    if (pid > 0)
    {
        close(client_fd);
        printf("Server \n");
        google_breakpad::CrashGenerationServer server(server_fd, OnClientDumpRequestCallback, nullptr, nullptr, nullptr,
                                                      true, &dump_path);
        server.Start();
        int status = 0;
        waitpid(pid, &status, 0);
        server.Stop();
    }
    else
    {
        close(server_fd);
        printf("Client\n");
        google_breakpad::MinidumpDescriptor descriptor(server_fd);
        google_breakpad::ExceptionHandler h(descriptor, nullptr, CrashCallback, nullptr, true, client_fd);
        printf("Client crash\n");
        crash();
    }
    return 0;
}
