#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <sys/time.h>
#include <time.h>
#include <dirent.h>
#include <pwd.h>
#include <pthread.h>

#include "nicinfo_shm.h"

#define SHM_PATH  "/share/sys_netcard_shm_path"
#define SEM_PATH  "/share/sys_netcard_sem_path"
#define LOG_PATH  "/var/log/netcard/"

typedef struct net_info{
	NETCARD_INFO info[MAXNICNUM];
}SHM;

static int semid = 0;
char log_path[1024];
char shm_path[1024];
char sem_path[1024];
SHM *ptr = NULL;
static char process_name[32] = "get_nic_info";

static void linx_free_shm( void *addr, int size );

#if 0
static pthread_mutex_t  lock_record_log = PTHREAD_MUTEX_INITIALIZER;
#define LOG_LOCK pthread_mutex_lock(&lock_record_log)
#define LOG_UNLOCK pthread_mutex_unlock(&lock_record_log)

static int is_checkdir = 0;

static void *record_log_thread( void *arg )
{
  char *log_str = (char *)arg;
	FILE *log_fp = NULL;

	 LOG_LOCK;
	if( !is_checkdir ) {
		create_dir( log_path );
		is_checkdir = 1;
	}
	 create_dir( log_path );
        if((log_fp = fopen(log_path, "a")) != NULL){
                if(fwrite(log_str, 1, strlen(log_str), log_fp) < 1){
                }
                fclose(log_fp);
        }
	
	LOG_UNLOCK;
	free(log_str);
	return NULL;
}

/* write error in logfile */
void record_log(char *str)
{
#if 0
        time_t tamp;
        char str_tm[4];
        char log_str[512];
        FILE *log_fp = NULL;
        struct tm tmptr;
        struct timeval tv;
        struct timezone tz;

        if((log_fp = fopen(log_path, "a")) != NULL){
                tamp = time(NULL);
                memset(str_tm, 0, sizeof(str_tm));
                memset(log_str, 0, sizeof(log_str));
                localtime_r(&tamp, &tmptr);
                gettimeofday(&tv, &tz);
                snprintf(str_tm, sizeof(str_tm), "%d", (int)tv.tv_usec/1000);
		if(str_tm[1] == '\0')str_tm[1] = '0';
		if(str_tm[2] == '\0')str_tm[2] = '0';
                strftime(log_str, sizeof(log_str), "%F %T.", &tmptr);
                strcat(log_str, str_tm);
                strcat(log_str, " ");
                strcat(log_str, "get_nic_info");
                strcat(log_str, " ");
                strcat(log_str, str);
                if(fwrite(log_str, 1, strlen(log_str), log_fp) < 1){
                }
                fclose(log_fp);
        }
#else
        time_t tamp;
        char str_tm[4];
        char log_str[512];
//        FILE *log_fp = NULL;
        struct tm tmptr;
        struct timeval tv;
        struct timezone tz;

//        if((log_fp = fopen(log_path, "a")) != NULL){
                tamp = time(NULL);
                memset(str_tm, 0, sizeof(str_tm));
                memset(log_str, 0, sizeof(log_str));
                localtime_r(&tamp, &tmptr);
                gettimeofday(&tv, &tz);
                snprintf(str_tm, sizeof(str_tm), "%d", (int)tv.tv_usec/1000);
		if(str_tm[1] == '\0')str_tm[1] = '0';
		if(str_tm[2] == '\0')str_tm[2] = '0';
                strftime(log_str, sizeof(log_str), "%F %T.", &tmptr);
                strcat(log_str, str_tm);
                strcat(log_str, " ");
                strcat(log_str, "get_nic_info");
                strcat(log_str, " ");
                strcat(log_str, str);
//                if(fwrite(log_str, 1, strlen(log_str), log_fp) < 1){
//                }
//                fclose(log_fp);
//        }

{
	pthread_t pid;
	char *keepstr = strdup( log_str );
	pthread_create( &pid, NULL, record_log_thread, (void *)keepstr);
}
#endif
}
#else

#include "common.c"

#endif

void get_sem(int semid)
{
	char err_str[200];
        struct sembuf lock[2];

        lock[0].sem_num = 0;
        lock[0].sem_op = -1;
        lock[0].sem_flg = SEM_UNDO;

/*        lock[1].sem_num = 0;
        lock[1].sem_op = 1;
        lock[1].sem_flg = SEM_UNDO;*/

        while(semop(semid, lock, 1)){
                if (errno == EINTR) {
                        continue;
                }
		snprintf(err_str, sizeof(err_str), "EMERG: semop():\n", strerror(errno));
		record_log(err_str);
		return;
        }
}

void release_sem(int semid)
{
        int ret;
	char err_str[200];
        struct sembuf unlock;

        unlock.sem_num = 0;
        unlock.sem_op = 1;
        unlock.sem_flg = SEM_UNDO;

        if((ret = semop(semid, &unlock, 1)) == -1){
		snprintf(err_str, sizeof(err_str), "EMERG: semop():\n", strerror(errno));
		record_log(err_str);
		return;
        }
}

static int global_share_id = -1;
static void *global_shmptr = NULL;

int init_nic_info(void)
{
	int fd = -1;
	int sem_val;
	char err_str[200];
	key_t key;
	
#if 0
	if ((key=ftok(sem_path, SEM_PROJ_ID)) == -1) {
		snprintf(err_str, sizeof(err_str), "EMERG: ftok():%s\n", strerror(errno));
		record_log(err_str);
		return -1;
	}
#else
	key = 0x1d5200;
#endif
	if((semid = semget(key, 1, 0666)) == -1){
		snprintf(err_str, sizeof(err_str), "EMERG: Create semaphore error: %s\n", strerror(errno));
		record_log(err_str);
		return -1;
	}
	/*
	if((sem_val = semctl(semid, 0, GETVAL, 0)) == -1){
		snprintf(err_str, sizeof(err_str), "EMERG: semctl: %s !\n", strerror(errno));
		record_log(err_str);
		semctl(semid, 0, IPC_RMID);
		return -1;
	}
	if(!sem_val){
		if(semctl(semid, 0, SETVAL, 1) == -1){
			snprintf(err_str, sizeof(err_str), "EMERG: semctl: %s !\n", strerror(errno));
			record_log(err_str);
			semctl(semid, 0, IPC_RMID);
			return -1;
		}
	}
	*/
#ifdef USE_OLD_MMSHARE
	if((fd = open(shm_path, O_RDONLY)) == -1){
		snprintf(err_str, sizeof(err_str), "EMERG: Error open %s: %s!\n",shm_path, strerror(errno));
		record_log(err_str);
		return -1;
	}
	ptr = (SHM*)mmap(NULL, sizeof(SHM), PROT_READ, MAP_SHARED, fd, 0);
	if(ptr == MAP_FAILED){
		snprintf(err_str, sizeof(err_str), "EMERG: mmap():%s\n", strerror(errno));
		record_log(err_str);
		return -1;
	}
	close(fd);
#else
	{
	void* shmptr = NULL;
	int size = 0;
	key_t share_key;
	int share_id = 0;
	char *ref_count = NULL;
	char *flag_str = NULL;
	char *path = shm_path;

	size = sizeof(SHM);
	size = size + 16;

//	share_key = ftok(path, 0x000d5000);
	share_key = 0x1d5010;

#if 0
		snprintf( err_str, sizeof( err_str ), 
				"MSG: lib, shm, size:%d, key:0x%x(%d)\n", size, share_key, share_key);
		record_log(err_str);
#endif

	global_share_id = shmget( share_key, size, 0666 );
	if( global_share_id == -1 ) {
		snprintf( err_str, sizeof( err_str ), 
				"EMERG: fail shmget, %s, 0x%x\n", strerror(errno), share_key);
		record_log(err_str);
        	return -1;
	}

	shmptr = shmat( global_share_id, NULL, 0 );
	if( shmptr == (void *)-1 ) {
		snprintf( err_str, sizeof( err_str ), "EMERG: shmat fail.%s,0x%x\n", strerror(errno), share_key );
		record_log( err_str );
        	return -1;
	}

#if 0
	flag_str = (char *)shmptr+size-16;
	if( strcmp( flag_str, "D5001" ) != 0 ) {
		//first, do init.
		memset( shmptr, 0, size );
		strcpy( flag_str, "D5001" );
	}

	ref_count = (char *)shmptr+size-1;
	(*ref_count)++;
#endif

	global_shmptr = shmptr;
	ptr = (SHM *)shmptr;
	}
#endif

	return 0;
}

int get_nic_info(char *nic_name, NETCARD_INFO *net_info)
{
	int i,ret;
	time_t tamp;
	struct tm tmptr;
	char *s;
	char buf[128];
	char err_str[200];
	struct passwd *user;
	int shm_id;
	int shm_key = 0x1d6010;
	char *shm_buf;
#if 0
	snprintf(err_str, sizeof(err_str), "NOTICE: get nicinfo:%s !\n", nic_name);
	record_log(err_str);
#endif
	tamp = time(NULL);
	localtime_r(&tamp, &tmptr);
	
	if(log_path[0]==0){
		shm_id = shmget(shm_key,128,0666);
		if(shm_id < 0)	return -1;
		shm_buf = (char *)shmat(shm_id,NULL,0);
		if(shm_buf == (void *) -1) return -1;
		sprintf(log_path,"%s",shm_buf);
		sprintf(shm_path,"%s",shm_buf);
		sprintf(sem_path,"%s",shm_buf);
		shmdt(shm_buf);
		strcat(log_path,LOG_PATH);
		strcat(shm_path,SHM_PATH);
		strcat(sem_path,SEM_PATH);
	}
#if 0
	//remove
	if((dir = opendir(log_path)) == NULL){
		if(errno == ENOENT){
			strcpy(log_path, "/tmp/");
		}
	}
	closedir(dir);
#endif

	memset(buf, 0, sizeof(buf));
	strftime(buf, sizeof(buf), "%Y%m%d_", &tmptr);
	strcat(buf, "sys_nicmonitor.log");
	
	LOGPATH_LOCK;
	s = strrchr(log_path, '/');
	s++;
	*s = '\0';
	strcat(log_path, buf);
	LOGPATH_UNLOCK;
	
	if((ret = init_nic_info()) == -1){
		return -1;
	}
	get_sem(semid);
	for(i = 0; ptr->info[i].charname[0] != 0; i++){
		if(!strcmp(ptr->info[i].charname, nic_name)){
		//	get_sem(semid);
			memcpy(net_info, &ptr->info[i], sizeof(NETCARD_INFO));
			release_sem(semid);
#ifdef USE_OLD_MMSHARE
			munmap(ptr, sizeof(SHM));
#else
			linx_free_shm( ptr, sizeof(SHM) );
#endif
			return 0;
		}
	}
	release_sem(semid);
	snprintf(err_str, sizeof(err_str), "NOTICE: No information of %s !\n", nic_name);
	record_log(err_str);
#ifdef USE_OLD_MMSHARE
	munmap(ptr, sizeof(SHM));
#else
	linx_free_shm( ptr, sizeof(SHM) );
#endif
	return -1;
}

static void linx_free_shm( void *addr, int size )
{
	
	void *shmptr = addr;
	char err_str[200];

#if 0
	snprintf(err_str, sizeof(err_str), "NOTICE: free shm 0x%x, size:%d, glo:0x%x\n", addr, size, global_shmptr);
	record_log(err_str);
#endif

	if( shmptr == global_shmptr ) {
		char *ref_count = NULL;
		int is_last = 0;
//		int size = sizeof(SHM);

		ref_count = (char *)shmptr + size + 16 - 1;

		is_last = *ref_count == 1?1:0;

#if 0
	snprintf(err_str, sizeof(err_str), "NOTICE: lib, sref_count: %d, last:%d\n", *ref_count, is_last);
	record_log(err_str);
#endif

#if 0
		if( is_last ) {
			memset( shmptr, 0, size + 16 );
		}
#endif
		shmdt( shmptr );
//		shmctl( global_share_id, IPC_RMID, NULL );
//		if( is_last ) {
//			global_shmptr = NULL;
//			global_share_id = -1;
//		}
	}
	
}


