#ifdef _WIN32
#define _CRT_SECURE_NO_WARNINGS
#define _CRT_NONSTDC_NO_WARNINGS
#include <windows.h>
#include <io.h>
#include "../Win32/w32def.h"
#endif	//	_WIN32

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#ifdef __linux__
#include <sys/file.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <linux/limits.h>
#include <sys/shm.h>
#endif	//	__linux__
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "defines.h"
#include "shm.h"

/////////////////////////////////////////////////////////////////////////////

#define _IS_VALID_SHMID(id)				((id) >= 0)

/////////////////////////////////////////////////////////////////////////////

class CShmLocker
{
public:
	CShmLocker(CGlobalMutex &rMutex) :	m_bLocked(false),
										m_rMutex(rMutex)
	{
		m_bLocked = m_rMutex.Lock();
	}

	~CShmLocker(void)
	{
		if(m_bLocked)
			m_bLocked = !m_rMutex.Unlock();
	}

private:
	bool m_bLocked;
	CGlobalMutex &m_rMutex;
};

/////////////////////////////////////////////////////////////////////////////

CShm::CShm(void) :	m_nShmID(_INVALID_ID)
{
	memset(&m_uuid, 0, sizeof(m_uuid));
}

CShm::~CShm(void)
{
	Release();
}

int CShm::Create(const uuid_t &ruuid, size_t nCbShm, const char *pszDir)
{
	if(!pszDir)
		pszDir = "";

	size_t nLenReq = strlen(pszDir) + _UUID_STRING_LEN + 2;

	if(nLenReq > PATH_MAX)
	{
		TRACE("CShm::Create: directory name too long\n");
		errno = EINVAL;
		return -1;
	}

	int nRet = -1;
	char szUuid[_UUID_STRING_LEN + 1];
	char szShm[PATH_MAX];
	_uuid_unparse(&ruuid, szUuid, sizeof(szUuid));
	sprintf(szShm, "%s/%s.shm", pszDir, szUuid);

	if(m_mutex.Create(ruuid, pszDir) < 0)
		return -1;

	int nFdShm;
//	CShmLocker locker(m_mutex);

	if((nFdShm = ::open(szShm, O_RDWR | O_CREAT | O_TRUNC, _NUMBER_OF_THE_BEAST)) >= 0)
	{
		key_t shmKey;

		if((shmKey = ::ftok(szShm, 'R')) >= 0)
		{
			if((m_nShmID = ::shmget(shmKey, nCbShm, IPC_CREAT | _NUMBER_OF_THE_BEAST)) >= 0)
			{
				struct shmid_ds sds;
				memset(&sds, 0, sizeof(sds));

				if(!IpcStat(&sds))
				{
					if(!sds.shm_atime)
					{
						void *p = ::shmat(m_nShmID, NULL, 0);
						::shmdt(p);
						TRACE("CShm::Create: Created new SHM: ID: %d, Size: %zu\n", m_nShmID, nCbShm);
						nRet = 1;
					}
					else
					{
						TRACE("CShm::Create: Opened existing SHM: ID: %d, Size: %zu\n", m_nShmID, nCbShm);
						nRet = 0;
					}

					_uuid_copy(&m_uuid, &ruuid);
				}
				else
				{
					TRACE("CShm::Create: IpcStat failed - errno: %d!\n", errno);
				}
			}
			else
			{
				TRACE("CShm::Create: Failed to create SHM on Key: 0x%08X - errno: %d!\n", shmKey, errno);
			}
		}
		else
		{
			TRACE("CShm::Create: Failed to create shmKey - errno: %d!\n", errno);
		}

		close(nFdShm);
	}
	else
	{
		TRACE("CShm::Create: Failed to open '%s' - errno: %d!\n", szShm, errno);
	}

	return nRet;
}

long CShm::Release(void)
{
	long att = -1;
	CShmLocker locker(m_mutex);

	if(_IS_VALID_SHMID(m_nShmID))
	{
		att = GetNumAttached();

		if(att == 0)
		{
			TRACE("CShm::Release: attached: %ld - SHM removed!\n", att);
			IpcRmID();
		}
		else if(att > 0)
		{
			TRACE("CShm::Release: Still attached: %ld!\n", att);
		}

		m_nShmID = _INVALID_ID;
	}

	return att;
}

void* CShm::Attach(const void *pAddr, int shmflg)
{
	CShmLocker locker(m_mutex);

	if(!_IS_VALID_SHMID(m_nShmID))
	{
		TRACE("CShm::Attach: Invalid ShmID: %d!\n", m_nShmID);
		errno = EINVAL;
		return NULL;
	}

	void *p = ::shmat(m_nShmID, pAddr, shmflg);

	if(p == (void*)-1)
	{
		TRACE("CShm::Attach: Failed to attach memory - errno: %d!\n", errno);
		p = NULL;
	}
	else
	{
		TRACE("CShm::Attach: %p!\n", p);
	}

	return p;
}

void CShm::Detach(const void *pAddr)
{
	if(pAddr)
	{
		TRACE("CShm::Detach: %p!\n", pAddr);
		CShmLocker locker(m_mutex);
		::shmdt(pAddr);
	}
}

long CShm::GetNumAttached(void)
{
	long att = -1;
	struct shmid_ds sds;
	if(!IpcStat(&sds))
		att = (long)sds.shm_nattch;
	return att;
}

/////////////////////////////////////////////////////////////////////////////

int CShm::Ctl(int cmd, struct shmid_ds *pshd)
{
	if(!_IS_VALID_SHMID(m_nShmID))
	{
		TRACE("CShm::Ctl: Invalid ShmID: %d!\n", m_nShmID);
		errno = EINVAL;
		return -1;
	}

	return ::shmctl(m_nShmID, cmd, pshd);
}

int CShm::Ctl(int cmd)
{
	return Ctl(cmd, (struct shmid_ds*)NULL);
}

int CShm::Ctl(int cmd, struct shminfo *pinfo)
{
	return Ctl(cmd, (struct shmid_ds*)pinfo);
}

int CShm::Ctl(int cmd, struct shm_info *pinfo)
{
	return Ctl(cmd, (struct shmid_ds*)pinfo);
}

/////////////////////////////////////////////////////////////////////////////

int CShm::IpcStat(struct shmid_ds *buf)
{
	return Ctl(IPC_STAT, buf);
}

int CShm::IpcInfo(struct shminfo *si)
{
	return Ctl(IPC_INFO, si);
}

int CShm::IpcSet(struct shmid_ds *buf)
{
	return Ctl(IPC_SET, buf);
}

int CShm::IpcRmID(void)
{
	return Ctl(IPC_RMID);
}

int CShm::ShmStat(int index, struct shmid_ds *buf)
{
	return ::shmctl(index, SHM_STAT, buf);
}

int CShm::ShmInfo(struct shm_info *pinfo)
{
	return Ctl(SHM_INFO, pinfo);
}

int CShm::Lock(void)
{
	return m_mutex.Lock();
}

int CShm::Unlock(void)
{
	return m_mutex.Unlock();
}

long CShm::InterlockedIncrement(volatile long *pl)
{
	if(!pl)
	{
		TRACE("CShm::InterlockedIncrement: Invalid Argument!\n");
		return 0;
	}

	long l;
	m_mutex.Lock();
	l = ++(*pl);
	m_mutex.Unlock();
	return l;
}

long CShm::InterlockedDecrement(volatile long *pl)
{
	if(!pl)
	{
		TRACE("CShm::InterlockedDecrement: Invalid Argument!\n");
		return 0;
	}

	long l;
	m_mutex.Lock();
	l = --(*pl);
	m_mutex.Unlock();
	return l;
}

long CShm::InterlockedCompare(volatile long *pl, long comparand)
{
	if(!pl)
	{
		TRACE("CShm::InterlockedCompare: Invalid Argument!\n");
		return 0;
	}

	long l;
	m_mutex.Lock();
	l = *pl - comparand;
	m_mutex.Unlock();
	return l;
}

long CShm::InterlockedSet(volatile long *pl, long val)
{
	if(!pl)
	{
		TRACE("CShm::InterlockedSet: Invalid Argument!\n");
		return 0;
	}

	long l;
	m_mutex.Lock();
	l = *pl;
	*pl = val;
	m_mutex.Unlock();
	return l;
}

long CShm::InterlockedClear(volatile long *pl)
{
	if(!pl)
	{
		TRACE("CShm::InterlockedClear: Invalid Argument!\n");
		return 0;
	}

	long l;
	m_mutex.Lock();
	l = *pl;
	*pl = 0;
	m_mutex.Unlock();
	return l;
}

/////////////////////////////////////////////////////////////////////////////

void CShm::DumpIpcPerm(struct ipc_perm *ip)
{
	CSemaphore::DumpIpcPerm(ip);
}

void CShm::DumpShmidDs(struct shmid_ds *sid)
{
	CShm::DumpIpcPerm(&sid->shm_perm);
	printf("shm_segsz:  %zu\n", sid->shm_segsz);
	printf("shm_atime:  %lu\n", sid->shm_atime);
	printf("shm_dtime:  %lu\n", sid->shm_dtime);
	printf("shm_ctime:  %lu\n", sid->shm_ctime);
	printf("shm_cpid:  %hd\n", sid->shm_cpid);
	printf("shm_lpid:   %hd\n", sid->shm_lpid);
	printf("shm_nattch: %lu\n", sid->shm_nattch);
}
