#include "platform/process.h"

#include "platform/paths_platform.h"

#include <sys/types.h>
#include <unistd.h>

#include <cstdlib>
#include <filesystem>
#include <system_error>

namespace nebula::platform {

bool LaunchSiblingExecutable(const std::string& executable_name) {
    const auto directory = ExecutableDirectory();
    if (directory.empty() || executable_name.empty()) {
        return false;
    }

    const std::filesystem::path path = directory / executable_name;
    std::error_code error;
    if (!std::filesystem::exists(path, error)) {
        return false;
    }

    const pid_t pid = fork();
    if (pid < 0) {
        return false;
    }
    if (pid == 0) {
        execl(path.c_str(), path.c_str(), static_cast<char*>(nullptr));
        _exit(127);
    }
    return true;
}

}  // namespace nebula::platform
