#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/time.h>
#include <time.h>

#include "./include/db_adaptor.h"

#define  DBA_CFG	"./conf/db_adapotr.cfg"

_db_cfg  db_cfg;

int dba_read_cfg()
{
	char s[80],s1[80];
	int  len;
	unsigned char conf_state=0xFF;
  	FILE *fpConf;
  	_db_link *db_ptr=NULL;
    
    	memset(&db_cfg, 0x00, sizeof(_db_cfg));
    	
	fpConf = fopen(DBA_CFG,"rb");
	
	if(fpConf == NULL)
	{
		return 0;
	}
   
	strcpy(s,"");
	strcpy(s1,"");
	while(fgets(s,1024,fpConf) !=(char *)0)
	{
		if( (int *)strchr(s,'#') !=NULL) continue;
		if( !strlen(s) ) continue;      
		len = strlen(s);
		if(len < 2) continue;
		
		if(s[len-1] == 0x0d ||s[len-1] == 0x0a)
		{
			if(s[len-2] == 0x0d ||s[len-2] == 0x0a)
			{
				s[len-2] = 0;
				len -= 2;			
			}
			else
			{
				s[len-1] = 0;
				len -= 1;
			}
		}
		
		if(!strncasecmp(s,"[db0]",5))
		{
			conf_state = 0;
			db_ptr = &db_cfg.db_link[0];
			continue;
		}
		else if(!strncasecmp(s,"[db1]",5))
		{
			conf_state = 1;
			db_ptr = &db_cfg.db_link[1];						
			continue;
		}
		else if(!strncasecmp(s,"[db2]",5))
		{
			conf_state = 2;
			db_ptr = &db_cfg.db_link[2];						
			continue;
		}
		else if(!strncasecmp(s,"[db3]",5))
		{
			conf_state = 3;
			db_ptr = &db_cfg.db_link[3];						
			continue;
		}

		switch(conf_state)
		{	
			case 0:
			case 1:
			case 2:
			case 3:
	        		if(strncasecmp(s,"enable=",7)==0)
	        		{
	        			if(strncasecmp(&s[7],"on", 2) == 0)
	        				db_ptr->enable = 1;
	        			else
	        				db_ptr->enable = 0;
	        		}
				else if(strncasecmp(s,"role=",5)==0)
	        		{
	        			db_ptr->role = atoi(&s[5]);
	        		}
				else if(strncasecmp(s,"host_ip=",8)==0)
	        		{
	        			strcpy(db_ptr->str_host_ip, &s[8]); 
	        			db_ptr->host_ip = inet_addr(&s[8]);
	        		}
				else if(strncasecmp(s,"host_port=",10)==0)
	        		{
	        			db_ptr->host_port = atoi(&s[10]);
	        		}
				else if(strncasecmp(s,"db_name=",8)==0)
	        		{
	        			strcpy(db_ptr->db_name, &s[8]);
	        		}
				else if(strncasecmp(s,"client_name=",12)==0)
	        		{
	        			strcpy(db_ptr->client_name, &s[12]);
	        		}
				else if(strncasecmp(s,"client_pwd=",11)==0)
	        		{
	        			strcpy(db_ptr->client_pwd, &s[11]);
	        		}
			break;    	
      		}
	}
	
	fclose(fpConf);
	
	return 1;
}

int dba_crm_set_prefix_table_created()
{
	db_cfg.prefix_file_created = 1;

	return 1;
}

int dba_crm_get_prefix_table_flag()
{
	return 	db_cfg.prefix_file_created;
}
