#include    "unpthread.h"
#include    "unpipc.h"
#include    "pre_thread_model.h"
#include    "protocol.h"

sem_t *sem_mutex;
int main()
{
	servinfo_t *ptr;
	struct stat stat;
	int filed, count = 1;
	//int val;
	int shm_size;
	
	filed = Shm_open(SHM_NAME, O_RDONLY, FILE_MODE);
	Fstat(filed, &stat);
	//sem_mutex = Sem_open(SEM_NAME, 0);

	/*
	Sem_getvalue(sem_mutex, &val);
	fprintf(stderr, "** wait sema val = %d\n", val);
	Sem_wait(sem_mutex);
	Sem_getvalue(sem_mutex, &val);	
	fprintf(stderr, "** pid %ld has semaphore, value = %d\n", (long)getpid(), val);
	*/
	
	ptr = Mmap(NULL, stat.st_size, PROT_READ, MAP_SHARED, filed, 0);
	
	//while ( ptr->next != NULL )
	while ( strcmp(ptr->m_pszServName, END_OF_SHM))
	{
		if (ptr->m_pszServName == NULL || ptr->m_pszServName[0] == '\0')
		{
			fprintf(stderr, "no more data!!!\n");
			break;
		}
		
		fprintf(stderr, "[%d] ServName-> %s : IP Address-> %s : Type-> %d : Port-> %d : Monitor_yn-> %s\n", count, ptr->m_pszServName, ptr->m_szIpString, ptr->m_ServType, ptr->m_sPort, ptr->m_monitorYN);
		fprintf(stderr, "[%d] Change Time-> %ld : DeadCount-> %u : Status-> %d : DomainName-> %s\n", count, ptr->m_StatChgTime, ptr->m_DeadCount, ptr->m_Status, ptr->m_pszDomainName);

		//view Status 
		fprintf(stderr, "******************************** STATUS ********************************\n");
		fprintf(stderr, "[%d] Stamp-> %ld : domain-> %s : disk tot-> %llu : disk free-> %llu\n", count, ptr->ss.stamp, ptr->ss.du.domain, ptr->ss.du.total, ptr->ss.du.free);
		fprintf(stderr, "[%d] manual disable-> %d : upload level-> %d : disk backlog-> %d : disk percent-> %d\n", count, ptr->ss.du.manual_disable, ptr->ss.du.upload_level, ptr->ss.du.disk_backlog, ptr->ss.du.disk_percent);
		fprintf(stderr, "[%d] conn estab-> %d : conn total-> %d\n", count, ptr->ss.du.connection_established, ptr->ss.du.connection_total);
		fprintf(stderr, "[%d] traffic ip-> %u : traffic ib-> %u : traffic op-> %u : traffic ob-> %u\n", count, ptr->ss.du.traffic_ip, ptr->ss.du.traffic_ib, ptr->ss.du.traffic_op, ptr->ss.du.traffic_ob);
		fprintf(stderr, "[%d] HostName-> %s\n", count, ptr->ss.du.hostname);
		fprintf(stderr, "************************************************************************\n\n");

		//ptr->next = Mmap(NULL, (sizeof(servinfo_t)), PROT_READ, MAP_SHARED, filed, (sizeof(servinfo_t))*count);
		ptr++;
		count++;
	}
	Close(filed);
	shm_size = get_sizeof_shm();
	munmap((void *)ptr, shm_size);	
	//Sem_post(sem_mutex);
	//Sem_close(sem_mutex);
	exit(0);
}

int get_sizeof_shm()
{
	struct stat stat;

	int memsize;
	int filed;

	/***        Posix Semaphore         ***/
	filed = Shm_open(SHM_NAME, O_RDWR, FILE_MODE);
	Fstat(filed, &stat);
	Close(filed);
	/* get size of mapping memory */
	memsize = stat.st_size;
	return memsize;
}
