#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/ipc.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 "nicinfo_shm.h"

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

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

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

/* write error in logfile */
void record_log(char *str)
{
        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);
        }
}

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

        lock[0].sem_num = 0;
        lock[0].sem_op = 0;
        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, 2)){
                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;
        }
}


int init_nic_info(void)
{
	int fd = -1;
	int sem_val;
	char err_str[200];
	key_t key;
	

	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;
	}
	if((semid = semget(key, 1, IPC_CREAT|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;
		}
	}
	*/
	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);
	
	return 0;
}
int get_nic_info(char *nic_name, NETCARD_INFO *net_info)
{
	int i,ret;
	time_t tamp;
	struct tm tmptr;
	DIR *dir;
	char *s;
	char buf[128];
	char err_str[200];
	struct passwd *user;

	tamp = time(NULL);
	localtime_r(&tamp, &tmptr);

	if((user = getpwnam("d5000"))!= NULL){
		sprintf(log_path,"%s",user->pw_dir);
		sprintf(shm_path,"%s",user->pw_dir);
		sprintf(sem_path,"%s",user->pw_dir);
	}
	strcat(log_path,LOG_PATH);
	strcat(shm_path,SHM_PATH);
	strcat(sem_path,SEM_PATH);

	if((dir = opendir(log_path)) == NULL){
		if(errno == ENOENT){
			strcpy(log_path, "/tmp/");
		}
	}
	closedir(dir);
	s = strrchr(log_path, '/');
	s++;
	*s = '\0';
	memset(buf, 0, sizeof(buf));
	strftime(buf, sizeof(buf), "%Y%m%d_", &tmptr);
	strcat(buf, "sys_nicmonitor");
	strcat(buf, ".log");
	strcat(log_path, buf);
	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);
			munmap(ptr, sizeof(SHM));
			return 0;
		}
	}
	release_sem(semid);
	snprintf(err_str, sizeof(err_str), "NOTICE: No information of %s !\n", nic_name);
	record_log(err_str);
	munmap(ptr, sizeof(SHM));
	return -1;
}
