/*************************************************
File name:	cdrdb.c
Author: 	
Version:	9:00:00 
Date:  		2002-5-7
Description:该文件实现了cdrCollector模块的数据库操作，并且定时的对数据库数据进行备份，
			通过保存csv数据文件
			
			
			
												
History:               
No. 		
Author:		  
Date:		 
Version:	   
Description:
*************************************************/
 
#include "cdr.h"
#include "../../../omcLib/c_program/ftp/ftp.h"   
static MYSQL *cdrdb_conn;   
static MYSQL *omcPub_conn;
extern cdr_src CdrSet[CDR_SRC_NUM];
extern BYTE iCdrNum;

static BYTE 	backup_flag=0;
static char tb_name[64][48];
static int cdr_index = 0, tb_index = 0, tb_num = 0;
static char compress_file[64];
static char send_file[64];
static char sening_dir[128];

void enum_cdrdb();
void backup_table(char *tb_name, char *csv_path,int flag,char *selfield,BYTE cdr_ver);
void create_csv(char *tb_name, char *csv_path,int flag,char *selfield);
void create_dat_for_wxc1(char *tb_name,char *csv_path,int flag,char *selfield);
void compress_csv(char *path_name);
//void chfilename(char *path_name, char *oldname);
void delfile(char *path_name,char *filename);
void clear_table(char *tb_name);
void send_csv(char *path_name);

/*************************************************
Function:        // cdrdb_init
Description:     // 初始化数据库，打开数据库的连接，获得数据库初始化参数
Calls:           // mysql_init; mysql_real_connect; mysql_query;
Called By:       // cdrmain.c:cdr_init; 
Table Accessed:  // OMC_PUB.omcPubVarConf; CDR_DB.cdrPubVarConf;
Table Updated:   // 
Input:           // 
Output:          // 
Return:          // 
Others:          // 
*************************************************/
void cdrdb_init()
{
	char sqlstr[256];
	MYSQL_RES *res;
	MYSQL_ROW row;
	
	BYTE m_state = 1;
	
	//初始化数据库
	while ((cdrdb_conn = mysql_init(NULL)) == NULL) {
		printf("Fail to init mysql:%s\n", mysql_error(cdrdb_conn));
		sleep(2);
	}
	
	//初始化数据库连接
	while (mysql_real_connect
		   (cdrdb_conn, "localhost", "root", "rootaa", "CDR_DB", 0, NULL,
			0) == NULL) {
		printf("Fail to init mysql:%s\n", mysql_error(cdrdb_conn));
		sleep(2);
	}

	//获取公共参数sending_directory的值
	sprintf(sqlstr,
			"SELECT pubVarValue FROM CDR_DB.cdrPubVarConf WHERE pubVarName='sending_directory'");
	
	if (mysql_query(cdrdb_conn, sqlstr) != 0) {
		cdr_log("%s\n", mysql_error(cdrdb_conn));
		return;
	}
	
	if ((res = mysql_store_result(cdrdb_conn)) == NULL)
		return;

	if((row = mysql_fetch_row(res)) != NULL) {
		strcpy(sening_dir,row[0]);
	}

	mysql_free_result(res);	

	while ((omcPub_conn = mysql_init(NULL)) == NULL) {
		printf("Fail to init mysql:%s\n", mysql_error(omcPub_conn));
		sleep(2);
	}

	while (mysql_real_connect
		   (omcPub_conn, "localhost", "root", "rootaa", "OMC_PUB", 0, NULL,
			0) == NULL) {
		printf("Fail to init mysql:%s\n", mysql_error(omcPub_conn));
		sleep(2);
	}
	
	//获得公共参数cdr_store_server的值
	sprintf(sqlstr,
			"SELECT pubVarValue FROM OMC_PUB.omcPubVarConf WHERE pubVarName='cdr_store_server'");
				
	if (mysql_query(omcPub_conn, sqlstr) != 0) {
		cdr_log("%s\n", mysql_error(omcPub_conn));
		return;
	}

	if ((res = mysql_store_result(omcPub_conn)) == NULL){
		return;
	}
	
	//判断是否需要备份
	if((row = mysql_fetch_row(res)) != NULL) {
		if(strlen(row[0]) == 0)
		{	
			backup_flag=0;
		}	
		else
		{	
			backup_flag=1;
		}
	}

	mysql_free_result(res);
	
	
/*
	while (m_state != 0) {
		switch (m_state) {
		case 1:				//find tables in CDR_DB
			if (cdr_index < iCdrNum) {
				enum_cdrdb();
				m_state = 2;
			} else
				m_state = 5;
			break;
		case 2:				//backup table
			if (tb_index < tb_num) {
				backup_table(tb_name[tb_index],
							 CdrSet[cdr_index - 1].csv_path);
				m_state = 3;
			} else
				m_state = 1;
			break;
		case 3:				//delete old records
			clear_table(tb_name[tb_index]);
			tb_index++;
			m_state = 4;
			break;
		case 4:				//don't compress csv files
			//compress_csv(CdrSet[cdr_index-1].csv_path);
			m_state = 2;
			break;
		case 5:				//finish
			cdr_index = 0;
			tb_index = 0;
			m_state = 0;
			return;
		}
	}*/
			cdr_index = 0;
			tb_index = 0;
			m_state = 0;
			return;
}

/*************************************************
Function:        // cdrdb_timer
Description:     // 每小时做一些固定的数据库操作，比如备份数据,删除旧的记录等
Calls:           // backup_table; enum_cdrdb; clear_table; 
Called By:       // cdrmain.c:cdr_timer; 
Table Accessed:  // 数据表
Table Updated:   // 
Input:           // 
Output:          // 
Return:          // 
Others:          // 
*************************************************/
void cdrdb_timer()
{
	unsigned long l_time;
	struct tm *t;
	static BYTE m_state = 0;
	
	//for backup table per hour
	int h_cdr_index=0;
	//for backup table per hour
	char h_tb_name[64];
	int flag;
	
	l_time = time(NULL);
	t = localtime(&l_time);

	if(t->tm_min==0){
		for(h_cdr_index=0;h_cdr_index<iCdrNum;h_cdr_index++){
			if(t->tm_hour==0){
				sprintf(h_tb_name,"%s_%d",CdrSet[h_cdr_index].record_table,23);
				flag=1;
			}else{
				sprintf(h_tb_name,"%s_%02d",CdrSet[h_cdr_index].record_table,t->tm_hour-1);
				flag=0;
			}
			backup_table(h_tb_name, CdrSet[h_cdr_index].csv_path,flag,CdrSet[h_cdr_index].define.field_select,CdrSet[h_cdr_index].cdr_ver);
//			send_csv(CdrSet[h_cdr_index].csv_path);
		}
	}		

	switch (m_state) {
	//IDLE
	case 0:					
		l_time = time(NULL);
		t = localtime(&l_time);
		if (t->tm_hour == 3) {
			m_state = 1;
			cdr_index = 0;
			tb_index = 0;
		}
		break;
	//find tables in CDR_DB	
	case 1:					
		if (cdr_index < iCdrNum) {
			enum_cdrdb();
			m_state = 2;
		} else
			m_state = 5;
		break;
	//backup table	
	case 2:					
		if (tb_index < tb_num) {
			//backup_table(tb_name[tb_index], CdrSet[cdr_index-1].csv_path,1,CdrSet[cdr_index-1].define.field_select,CdrSet[cdr_index-1].cdr_ver);
			m_state = 3;
		} else
			m_state = 1;
		break;
	//delete old records	
	case 3:					
		clear_table(tb_name[tb_index]);
		tb_index++;
		m_state = 4;
		break;
	//compress csv files	
	case 4:					
		//compress_csv(CdrSet[cdr_index].csv_path);
		m_state = 2;
		break;
	//finish	
	case 5:					
		l_time = time(NULL);
		t = localtime(&l_time);
		if (t->tm_hour != 3) {
			cdr_index = 0;
			tb_index = 0;
			m_state = 0;
		}
		break;
	}
}

/*************************************************
Function:        // enum_cdrdb
Description:     // 找出所有的数据表，以便下一步操作
Calls:           // mysql_query; mysql_store_result; mysql_fetch_row;
Called By:       // cdrdb_timer;
Table Accessed:  // 数据表
Table Updated:   // 
Input:           // 
Output:          // 
Return:          // 
Others:          // 
*************************************************/
void enum_cdrdb()
{
	cdr_src *pcdr;
	char sqlstr[64];
	MYSQL_RES *res_set;
	MYSQL_ROW row;
	int i;

	tb_index = tb_num = 0;

	pcdr = &CdrSet[cdr_index++];

	for (i = 0; i < cdr_index - 2; i++) {
		if (strstr(CdrSet[i].record_table, pcdr->record_table) != NULL) {
			cdr_index++;
			return;
		}
	}

	cdr_log("Search tables like %s*\n", pcdr->record_table);

	sprintf(sqlstr, "SHOW TABLES FROM CDR_DB LIKE '%s_%%'",
			pcdr->record_table);
	if (mysql_query(cdrdb_conn, sqlstr) != 0)
		return;
	if ((res_set = mysql_store_result(cdrdb_conn)) == NULL)
		return;
	while ((row = mysql_fetch_row(res_set)) != NULL && tb_num < 64) {
		if (row[0] != NULL)
			strcpy(tb_name[tb_num++], row[0]);
	}
	mysql_free_result(res_set);

}

/*************************************************
Function:        // backup_table
Description:     // 备份数据表，为生成csv文件做些准备工作
Calls:           // mysql_query; mysql_store_result; mysql_fetch_row; create_dat_for_wxc1; create_csv;
Called By:       // cdrdb_timer;
Table Accessed:  // 数据表
Table Updated:   // 
Input:           // tb_name:表名; csv_path:保存路径; flag:标志位; selfield; cdr_ver:版本;
Output:          // 
Return:          // 
Others:          // 
*************************************************/
void backup_table(char *tb_name, char *csv_path,int flag,char *selfield,BYTE cdr_ver)
{
	char sqlstr[256];
	MYSQL_RES *res_set;
	MYSQL_ROW row;
	char timestr[50];
	//char          mytime[20],myday[20];
	long l_time;
	struct tm *t;

	cdr_log("Start backup table %s\n", tb_name);
	if(flag==1)
		sprintf(sqlstr,
			"SELECT DATE_FORMAT(releaseTime,'%%Y_%%m_%%d') FROM %s WHERE TO_DAYS(releaseTime)<TO_DAYS(NOW()) LIMIT 1",
			tb_name);
	else
		sprintf(sqlstr,
			"SELECT DATE_FORMAT(releaseTime,'%%Y_%%m_%%d') FROM %s WHERE TO_DAYS(releaseTime)=TO_DAYS(NOW()) LIMIT 1",
			tb_name);
	if (mysql_query(cdrdb_conn, sqlstr) != 0) {
		cdr_log("Fail to query:%s\n", mysql_error(cdrdb_conn));
		return;
	}
	if ((res_set = mysql_store_result(cdrdb_conn)) == NULL)
		return;

	if ((row = mysql_fetch_row(res_set)) == NULL || row[0] == NULL) {
		mysql_free_result(res_set);
		cdr_log("No old record in table\n");
		l_time = time(NULL);
		if(flag==1)
			l_time = l_time-24*3600;//for the yesterday
		t = localtime(&l_time);
		sprintf(timestr,"%04d_%02d_%02d",t->tm_year + 1900,	t->tm_mon + 1,t->tm_mday);
//		return;
	}else{
		strcpy(timestr, row[0]);
		mysql_free_result(res_set);
	}
	//根据版本号产生csv文件
	/*if(cdr_ver==1)
		create_dat_for_wxc1(tb_name, timestr, csv_path,flag,selfield);
	else
		create_csv(tb_name, timestr, csv_path,flag,selfield);*/
}

/*************************************************
Function:        // create_csv
Description:     // 生成csv文件
Calls:           // mysql_query;
Called By:       // backup_table;
Table Accessed:  // 数据表
Table Updated:   // 
Input:           // tb_name:表名; time_str:时间; csv_path:保存路径; flag:标志位; selfield; 
Output:          // 
Return:          // 
Others:          // 
*************************************************/
void create_csv(char *tb_name, char *csv_path,int flag,char *selfield)
{
	char olddir[128], sqlstr[1024], csv_file[32], tb_prefix[32], *pchr, cmdstr[1024];	//cur_path[96],dirname[32];
	struct stat fileinfo;
//	char filestr[]
//	MYSQL_RES *res_set;
//	MYSQL_ROW row;
	
	strcpy(tb_prefix, tb_name);
	if ((pchr = strchr(tb_prefix, '_')) == NULL)
		return;
	*(pchr++) = '\0';
	
	//获得上一次目录
	getcwd(olddir, 128);
	cdr_log("%s\n", tb_name);
	cdr_log("%s\n", csv_path);
	if (chdir(csv_path) == -1) {
		sprintf(cmdstr, "mkdir -p -m777 %s", csv_path);
		cdr_log("%s\n", cmdstr);
		system(cmdstr);
		if (chdir(csv_path) == -1)
			return;
	}
	
	//到sending_dir目录去，不存在则创建
	if (chdir(sening_dir) == -1) {
		sprintf(cmdstr, "mkdir -p -m777 %s", sening_dir);
		cdr_log("%s\n", cmdstr);
		system(cmdstr);
		if (chdir(sening_dir) == -1)
			return;
	}	

	//sprintf(csv_file, "%s_%s_%s.csv", tb_prefix, time_str, pchr);
	sprintf(csv_file, "%s", cdrFileName);
	//chfilename(csv_path, csv_file);
	delfile(csv_path, csv_file);
	cdr_log("%s\n", csv_path);
	cdr_log("%s\n", csv_file);
	cdr_log("%s\n", CDRDB_NAME);
	cdr_log("%s\n", tb_name);
//*************************************************************
	//生成csv文件
	if(flag==1)
		sprintf(sqlstr,
			"SELECT %s INTO OUTFILE '%s/%s' FROM %s.%s ",
			selfield,csv_path, csv_file, CDRDB_NAME, tb_name);
	else
		sprintf(sqlstr,
			"SELECT %s INTO OUTFILE '%s/%s' FROM %s.%s ",
			selfield,csv_path, csv_file, CDRDB_NAME, tb_name);
	//sprintf(sqlstr,"SELECT * INTO OUTFILE '%s/%s' FIELDS TERMINATED BY ',' FROM %s.%s WHERE TO_DAYS(releaseTime)<TO_DAYS(NOW())",csv_path,csv_file,CDRDB_NAME,tb_name);
	printf("%s\n", sqlstr);
	if (mysql_query(cdrdb_conn, sqlstr) != 0) {
		printf("Fail to create csv:%s\n", mysql_error(cdrdb_conn));
		{
			chdir(olddir);
			return;
		}
	} else {
		//if(backup_flag)
		{	
			//把生成的csv文件移动到指定的保存路径
			sprintf(send_file,"%s",csv_file);
			sprintf(cmdstr, "cp %s/%s %s/%s.bak",csv_path,csv_file,csv_path,csv_file);
			system(cmdstr);
			sprintf(cmdstr, "mv %s/%s.bak %s/%s",csv_path,csv_file,sening_dir,csv_file);		
			system(cmdstr);	
		}
		if (stat(csv_file, &fileinfo) == 0) 
		{
			/*if (fileinfo.st_size == 0) {
				cdr_log("zero size,delete file %s\n", csv_file);
				remove(csv_file);
			} else*/				
			strcpy(compress_file, csv_file);
		}
	}

	//chdir(olddir);

}

/*************************************************
Function:        // clear_table
Description:     // 删除旧的数据表
Calls:           // mysql_query; mysql_store_result; mysql_fetch_row;
Called By:       // cdrdb_timer;
Table Accessed:  // 数据表
Table Updated:   // 
Input:           // tb_name:表名; 
Output:          // 
Return:          // 
Others:          // 
*************************************************/
void clear_table(char *tb_name)
{
	char sqlstr[256];
	MYSQL_RES *res_set;
	MYSQL_ROW row;
	cdr_log("clear table %s...", tb_name);
	//删除过期的数据表
	sprintf(sqlstr,
			"DELETE FROM %s.%s ",
			CDRDB_NAME, tb_name);
	if (mysql_query(cdrdb_conn, sqlstr) != 0) {
		cdr_log("Fail to clear table:%s\n", mysql_error(cdrdb_conn));
		return;
	}
/*
	cdr_log("optimizing...\n");
	sprintf(sqlstr, "OPTIMIZE TABLE %s", tb_name);
	if (mysql_query(cdrdb_conn, sqlstr) != 0) {
		cdr_log("Fail to optimizing table:%s\n", mysql_error(cdrdb_conn));
		return;
	}
	if ((res_set = mysql_store_result(cdrdb_conn)) != NULL) {
		while ((row = mysql_fetch_row(res_set))) {
			cdr_log("%s/%s/%s/%s\n", row[0], row[1], row[2], row[3]);
		}
	}
	mysql_free_result(res_set);*/
}

/*************************************************
Function:        // compress_csv
Description:     // 压缩csv文件
Calls:           // 
Called By:       // cdrdb_timer;
Table Accessed:  // 数据表
Table Updated:   // 
Input:           // path_name:路径名; 
Output:          // 
Return:          // 
Others:          // 
*************************************************/
void compress_csv(char *path_name)
{
	char olddir[128], *pchr, file_prefix[64], csv_file[64], tarfile[64],
		cmdstr[128];
	DWORD oldmask;

	//非法文件
	if (strlen(compress_file) < 1)
		return;

	cdr_log("start compress file '%s' in %s\n", compress_file, path_name);

	strcpy(csv_file, compress_file);
	strcpy(file_prefix, compress_file);
	compress_file[0] = '\0';

	//不是csv文件
	if ((pchr = strstr(file_prefix, ".csv")) == NULL)
		return;
	*(pchr) = '\0';

	getcwd(olddir, 128);
	if (chdir(path_name) == -1)
		return;

	sprintf(tarfile, "%s.tgz", file_prefix);
	//chfilename(path_name, tarfile);
	delfile(path_name, tarfile);

	//开始压缩
	oldmask = umask(0);
	sprintf(cmdstr, "tar zvfc ./%s ./%s", tarfile, csv_file);
	system(cmdstr);
	umask(oldmask);

	if (access(tarfile, F_OK) == 0)
		remove(csv_file);
	else {
		cdr_log("Fail to compress csv file %s\n", csv_file);
		chdir(olddir);
		return;
	}

	chdir(olddir);
}

/*
void chfilename(char *path_name, char *oldname)
{
	char newname[64], newpath[96];
	int n = 0;
	strcpy(newname, oldname);
	sprintf(newpath, "%s/%s", path_name, newname);
	while (access(newpath, F_OK) == 0) {
		sprintf(newname, "%s~%d", oldname, n++);
		sprintf(newpath, "%s/%s", path_name, newname);
	}
	cdr_log("File %s/%s exist.change it's name to %s\n", path_name,
			oldname, newname);
	strcpy(oldname, newname);
}
*/

/*************************************************
Function:        // delfile
Description:     // 删除指定的文件
Calls:           // 
Called By:       // create_csv;
Table Accessed:  // 
Table Updated:   // 
Input:           // path_name:路径名; file_name:文件名
Output:          // 
Return:          // 
Others:          // 
*************************************************/
void delfile(char *path_name, char *filename)
{
	char path[96];

	sprintf(path, "%s/%s", path_name, filename);
	if(access(path, F_OK) == 0) {
		unlink(path);
	}
	cdr_log("File %s/%s exist.It has been deleted for the new file\n", path_name,
			filename);
}

/*************************************************
Function:        // safe_query
Description:     // 数据库查询函数
Calls:           // mysql_ping；
Called By:       // 
Table Accessed:  // 
Table Updated:   // 
Input:           // conn:数据库连接; strquery:sql语句; retry:重试次数
Output:          // 
Return:          // 
Others:          // 这是一个递归函数，在次模块没有被调用
*************************************************/
int safe_query(MYSQL * conn, char *strquery, int retry)
{
	int errno;
	if (mysql_query(conn, strquery) == 0) {
		return 0;
	} else {
		errno = mysql_errno(conn);
		if (errno == CR_SERVER_GONE_ERROR || errno == CR_SERVER_LOST) {
			retry %= 5;
			cdr_log("error NO.:%d,retry...remain %d times\n", errno,
					retry);
			if (mysql_ping(conn)) {
				cdr_log("lost connection to mysql server\n");
				return 1;
			}

			if (retry-- > 0)
				return safe_query(conn, strquery, retry);
			else {
				cdr_log("%s\n", strquery);
				cdr_log("error %d:%s\n", mysql_errno(conn),
						mysql_error(conn));
				cdr_log("can't fix the error\n");
				return 1;
			}
		} else {
			cdr_log("%s\n", strquery);
			cdr_log("error %d:%s\n", mysql_errno(conn), mysql_error(conn));
			return 1;
		}
	}

}

/*************************************************
Function:        // send_csv
Description:     // 发送csv文件到指定发目录
Calls:           // mysql_query; mysql_store_result; mysql_fetch_row;
Called By:       // 
Table Accessed:  // 
Table Updated:   // 
Input:           // 
Output:          // 
Return:          // 
Others:          // 此函数已废弃不用
*************************************************/
void send_csv(char *path_name)
{
	/*char serverinfo[128],sqlstr[256],*username,*pwd,*serverip,*remotepath, *pchr;
	char locationpath[128];
	char sendpath[128];
	char getpath[128];
	char localIP[16][16];	
	
	MYSQL_RES *res;
	MYSQL_ROW row;
	
	int nRet,tmppathlen,count;

	if(*send_file==0){
		return;
	}			
	sprintf(sqlstr,
			"SELECT pubVarValue FROM OMC_PUB.omcPubVarConf WHERE pubVarName='cdr_store_server'");
	
	if (mysql_query(omcPub_conn, sqlstr) != 0) {
		cdr_log("%s\n", mysql_error(omcPub_conn));
		return;
	}
	if ((res = mysql_store_result(omcPub_conn)) == NULL)
		return;

	if((row = mysql_fetch_row(res)) != NULL) {
		memset(serverinfo, 0, sizeof(serverinfo));
		strcpy(serverinfo,row[0]);
	}
	
	mysql_free_result(res);


	tmppathlen =0;
	tmppathlen = strlen(serverinfo);
	if (serverinfo[tmppathlen-1] != '/'||tmppathlen<127){
		serverinfo[tmppathlen]='/';
		serverinfo[tmppathlen+1]='\0';
		//strcat(serverinfo,"/");
	}
			
	username= serverinfo;//get username

	if((pchr = strstr(serverinfo, "@"))==NULL){
		cdr_log("send csv files error,cdr_store_server param error!\n");
		return;
	}
	*(pchr++) = '\0';
	serverip = pchr;		//get server ip
	if((pchr = strstr(username, ":"))==NULL){
		cdr_log("send csv files error,cdr_store_server param error!\n");
		return;
	}
	*(pchr++) = '\0';
	pwd = pchr;//get password
	if((pchr = strstr(serverip, ">"))==NULL){
		cdr_log("send csv files error,cdr_store_server param error!\n");
		return;
	}
	*(pchr++) = '\0';
	remotepath = pchr;//get remotepath
*/
//****************************************
//不能往存放cdr的目录上传
//****************************************
//	serverip+remotepath  eg:172.18.234.235/tmp/	
	/*sprintf(sendpath,"%s%s",serverip,remotepath);
	
	nRet=ftp_getlocalip(localIP);	
	if(nRet>16) nRet=16;
	for(count=0;count<nRet;count++){
		sprintf(getpath,"%s%s/",localIP[count],path_name);
		if(strcmp(getpath,sendpath)==0){
//			printf("the same place..return\n");
			return;			
		}
	}*/	
//****************************************

	/*if((nRet=ftp_open(serverip,21)==1)){		
		cdr_log("send csv files error,%s->ftp open failed\n",ftp_retmsg);
		ftp_logout();
		return;
	}		
	if((nRet=ftp_login(username,pwd)==1)){			
		cdr_log("send csv files error,%s->ftp login failed\n",ftp_retmsg);
		ftp_logout();
		return;
	}
	
	if((nRet = ftp_cwd(remotepath)==1)){		
		cdr_log("send csv files error,%s->ftp CWD failed\n",ftp_retmsg);
		ftp_logout();
		return;
	}	

	sprintf(locationpath,"%s/",path_name);


	if((nRet = ftp_putfile(send_file,locationpath)==1)){
		cdr_log("send csv files error,%s->upload failed\n",ftp_retmsg);
		ftp_logout();	
		return; 
	} 
	ftp_logout();
	memset(send_file,0,64);
	return; */
}

/*************************************************
Function:        // create_dat_for_wxc1
Description:     // 当是wxc1的时候，用此函数备份数据表，产生csv文件
Calls:           // mysql_query; mysql_store_result; mysql_fetch_row;
Called By:       // backup_table;
Table Accessed:  // 数据表
Table Updated:   // 
Input:           // 
Output:          // 
Return:          // 
Others:          //
*************************************************/
void create_dat_for_wxc1(char *tb_name,char *csv_path,int flag,char *selfield)
{
	char olddir[128], sqlstr[1024], csv_file[32], tb_prefix[32], *pchr, cmdstr[1024];	//cur_path[96],dirname[32];
	int wcount=0;
	char dat_file[64];
	MYSQL_RES *res_set;
	MYSQL_ROW row;
	FILE *dat_fp;
	
	unsigned long l_time;
	struct tm *t;	
	char str[512];
	int res_num,i;
	int p_width[27]={8,18,23,23,23,23,23,11,11,16,7,7,22,23,23,23,15,9,7,23,7,7,7,23,23,11,9};
	//int p_width[28]={8,18,23,23,23,23,23,11,11,6,10,7,7,22,23,23,23,15,9,7,23,7,7,7,23,23,11,9};
	
	strcpy(tb_prefix, tb_name);
	if ((pchr = strchr(tb_prefix, '_')) == NULL)
		return;
	*(pchr++) = '\0';

	getcwd(olddir, 128);
	cdr_log("%s\n", tb_name);
	cdr_log("%s\n", csv_path);
	if (chdir(csv_path) == -1) {
		sprintf(cmdstr, "mkdir -p -m777 %s", csv_path);
		cdr_log("%s\n", cmdstr);
		system(cmdstr);
		if (chdir(csv_path) == -1)
			return;
	}
	
	if (chdir(sening_dir) == -1) {
		sprintf(cmdstr, "mkdir -p -m777 %s", sening_dir);
		cdr_log("%s\n", cmdstr);
		system(cmdstr);
		if (chdir(sening_dir) == -1)
			return;
	}	
	
	//sprintf(csv_file, "%s_%s_%s.csv", tb_prefix, time_str, pchr);
	sprintf(csv_file, "%s", cdrFileName);
	//chfilename(csv_path, csv_file);
	delfile(csv_path, csv_file);
	cdr_log("%s\n", csv_path);
	cdr_log("%s\n", csv_file);
	cdr_log("%s\n", CDRDB_NAME);
	cdr_log("%s\n", tb_name);

//*************************************************************
	if(flag==1)
		sprintf(sqlstr,
			"SELECT %s FROM %s.%s WHERE TO_DAYS(releaseTime)<TO_DAYS(NOW())",
			selfield, CDRDB_NAME, tb_name);
	else
		sprintf(sqlstr,
			"SELECT %s FROM %s.%s WHERE TO_DAYS(releaseTime)=TO_DAYS(NOW())",
//			"SELECT %s FROM %s.%s",
			selfield, CDRDB_NAME, tb_name);

	cdr_log("%s\n", sqlstr);
	
	if (mysql_query(cdrdb_conn, sqlstr) != 0) {
		cdr_log("%s\n", mysql_error(cdrdb_conn));
		return;
	}

	if ((res_set = mysql_store_result(cdrdb_conn)) == NULL) {
		cdr_log("%s\n", mysql_error(cdrdb_conn));
		return;
	}	
	
	
	sprintf(dat_file, "%s/%s", csv_path, csv_file);
	dat_fp = fopen(dat_file, "w");
	if(dat_fp==NULL){
		cdr_log("Fail to create file\n");
		chdir(olddir);
		return;
	}
	res_num = mysql_num_rows(res_set);
	l_time = time(NULL);
	t = localtime(&l_time);	
	
	fprintf(dat_fp,"FILE NAME: %s  NO. OF RECORDS:%-10d\n",dat_file,res_num);	

	fprintf(dat_fp,"START DATE: %02d/%02d/%d 	 START TIME: %02d:%02d:%02d\n\n",t->tm_mon+1,t->tm_mday,t->tm_year+1900,t->tm_hour,t->tm_min,t->tm_sec);
	fprintf(dat_fp,"Type    Imsi              Msisdn                 Msrn                   Calling #              Called #               RE                     In.TkGp    Ou.TkGp    Location        BS     SS     Mob. ClassMark        Seizure Time           Answer Time            Release Time           Duration       TCos     SSA    SS Parm.               SSR    CR     RCU    SM Delivery Time       SC Address             SM Rslt    MsgRf    \n\n");
		
	while ((row = mysql_fetch_row(res_set)) != NULL){
		if(atoi(row[0])!=6&&atoi(row[0])!=7){  //not sms
			if(row[16]==NULL||atoi(row[16])==0)  //Duration=0 skip
				continue;			
		}
		for(i=0;i<27;i++){
			if(row[i]==NULL){				
				if(i==7||i==8){
					;//In.TkGp,Ou.TkGpr skip
				}else{		
					fprintf(dat_fp,"%-*s",p_width[i],"--");
					continue;
				}
			}			
			switch (i){
				case 0: // Type
				case 10:// basicService 
				case 11:// supplServicesUsed  
				case 18:// SSA   
				case 20:// SSR  		
				case 26:// MsgRf  			
					sprintf(str,"%03d",atoi(row[i]));					
					break;
				case 7:// In.TkGp
				case 8:// Ou.TkGp
					if(atoi(row[0])==6||atoi(row[0])==7){//sms
						sprintf(str,"--");
					}else{
						sprintf(str,"00 00 00");
					}
					break;
				case 15:// releaseTime	
					if(atoi(row[0])==6||atoi(row[0])==7){
						fprintf(dat_fp,"%-*s",p_width[i],"--");
						continue;						
					}
				case 13:// seizureTime 
				case 14:// answerTime
				case 23:// SmDeliveryTime 					
					// 2001-06-07  11:12:22->
					// 06/07/2001  11:12:22			
					{
						int y=0,m=0,d=0;
						pchr=row[i];
						y = atoi(pchr);
						pchr = strchr(pchr,'-');
						if(pchr==NULL)
						{
							sprintf(str,"%02d/%02d/%02d %s",m,d,y,pchr);
							break;							
						}
						pchr++;
						m = atoi(pchr);
						pchr = strchr(pchr,'-');
						pchr++;
						if(pchr==NULL)
						{
							sprintf(str,"%02d/%02d/%02d %s",m,d,y,pchr);
							break;							
						}						
						d = atoi(pchr);
						pchr = strchr(pchr,' ');
						sprintf(str,"%02d/%02d/%02d %s",m,d,y,pchr);
						break;
					}
				case 16://callDuration
					{
						int d,h,m,s,total;
						total =atoi(row[i]);
						d = total/86400;
						h = (total%86400)/3600;
						m = (total%3600)/60;
						s = total%60;
						sprintf(str,"%02d:%02d:%02d:%02d",d,h,m,s);
						break;
					}
//				case 9:	// location_mscNumber 
//				case 10:// location_mscNumber_2
				case 17:// TCos					
					sprintf(str,"%05d",atoi(row[i]));					
					break;
				case 21:// CR
					sprintf(str,"%04d",atoi(row[i]));
					break;
					sprintf(str,"%s",row[i]);
					break;																
				case 12://	Mob. ClassMark
					sprintf(str,"1f %s",row[i]);	
					break;
				default:
					sprintf(str,"%s",row[i]);
					break;
			}
			fprintf(dat_fp,"%-*s",p_width[i],str);
		}
		fprintf(dat_fp,"\n");			
		wcount++;
	}
	fseek(dat_fp,0,SEEK_SET);
	fprintf(dat_fp,"FILE NAME: %s  NO. OF RECORDS:%-10d\n",dat_file,wcount);
	mysql_free_result(res_set);
	strcpy(compress_file, csv_file);
	fclose(dat_fp);
	chdir(olddir);	
	if(backup_flag)
	{	
		sprintf(send_file,"%s",csv_file);
		sprintf(cmdstr, "cp %s/%s %s/%s.bak",csv_path,csv_file,csv_path,csv_file);
		system(cmdstr);
		sprintf(cmdstr, "mv %s/%s.bak %s/%s",csv_path,csv_file,sening_dir,csv_file);		
		system(cmdstr);		
	}	
}
