#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 {
namespace {

std::filesystem::path ResolveSiblingPath(const std::string& executable_name) {
    const auto directory = ExecutableDirectory();
    if (directory.empty()) {
        return {};
    }

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

    // NebulaBrowser.app/Contents/MacOS -> sibling NebulaBigPicture.app/Contents/MacOS
    const std::filesystem::path sibling_app =
        directory / ".." / ".." / ".." / (executable_name + ".app") / "Contents" / "MacOS" /
        executable_name;
    if (std::filesystem::exists(sibling_app, error)) {
        return sibling_app.lexically_normal();
    }

    return {};
}

}  // namespace

bool LaunchSiblingExecutable(const std::string& executable_name) {
    const std::filesystem::path path = ResolveSiblingPath(executable_name);
    if (path.empty()) {
        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
