#include "shared_mem_buffer.h"

#include <QDebug>
#include <atomic>

#ifdef QT_POSIX_IPC
    // The POSIX backend can be explicitly selected using the -feature-ipc_posix
    // option to the Qt configure script. If it is enabled, the QT_POSIX_IPC
    // macro will be defined. -> we use SystemV shared memory
#error "QT_POSIX_IPC defined"
#else
#include <sys/ipc.h>    // ftok
#endif

// std::atomic_bool SharedMemBuffer::__sharedMemLocked{false};

QSharedMemory *SharedMemBuffer::getShm(std::size_t size) {
    static QSharedMemory shMem;
    if (size > 0) {
        static const long nativeKey = ftok("/etc/os-release", 'H');
        static const QString fkey = std::to_string(nativeKey).c_str();
        shMem.setKey(fkey);
        if (!shMem.isAttached()) {
            if (shMem.create(size)) {
                return &shMem;
            } else {
                if (shMem.error() == QSharedMemory::AlreadyExists) {
                    if (shMem.attach()) {
                        return &shMem;
                    }
                }
            }
            qCritical() << shMem.nativeKey() << shMem.key() << shMem.data()
                        << shMem.error() << shMem.errorString();
            return nullptr;
        }
    }
    return &shMem;
}
