#include <stdlib.h>
#include <errno.h>
#include "omcDbLib.h"

void exitLog(const char *fmt, ...);

int getOmcSysNo_pri(int* sysNo)
{
	char fileName[512];
	unsigned char buf[4096];
	unsigned char param[32][512];
	char paramName[128];
	char paramValue[384];
	char* temp;
	FILE* fp;
	int fi;
	int i;
	//int j;
	int paramCount;
	int byteCount;
	
	paramCount=0;
	byteCount=0;
	memset(buf,0,4096);
	memset(param,0,32*512);
	sprintf(fileName,"/usr/local/omc/bin/conf/omcd.conf");
	fp=fopen(fileName,"r");
	if(fp)
	{
		fi=fileno(fp);
		if(read(fi,buf,4096))
		{
			for(i=0;i<4096;i++)
			{	
				if(buf[i] == 0x0A)
				{
					//printf("\n");
					if(byteCount<512 && param[paramCount][0] != 0x00 && param[paramCount][0] != 0x23)
						paramCount++;
					else
						memset(param[paramCount],0,512);	
					byteCount=0;
				}	
				else
				{	
					param[paramCount][byteCount]=buf[i];
					byteCount++;
				}
				
				//printf("%02x ",buf[i]);
			}
			
			for(i=0;i<paramCount;i++)
			{
				temp=strtok((char*)param[i],"=");
				sprintf(paramName,"%s",temp);
				//printf("Name=%s,",temp);
				temp=strtok(NULL,"=");
				sprintf(paramValue,"%s",temp);
				//printf("Value=%s\n",temp);
				
				
				if(strcasecmp(paramName,"omcSysNo") == 0)
				{
					*sysNo=atoi(paramValue);
				}	
			}
		}	
		close(fi);
		fclose(fp);
	}	
	else
	{
		system("pwd");
		exitLog("omcDbLib:getOmcSysNo_pri, Can not open the omcd.conf");
		printf("%s,%s\n",strerror(errno),fileName);
		exit(1);
	}	
	return 1;
}

void insertSeriousAlarmLog(int compCode,int alarmCode)
{
	int omcSysNo=-1;
	char sqlstr[256];
	MYSQL * alarmConn;
	
	getOmcSysNo_pri(&omcSysNo);
	
	//connect
	while ((alarmConn = mysql_init(NULL)) == NULL) {
		fprintf(stderr, "Cannot initiate MySQL!!\n");
		Print("[ERR][insertSeriousAlarmLog]:Fail to connect OMC_PUB");
		sleep(2);
	}

	while (mysql_real_connect
		   (alarmConn, "localhost", USER_NAME, PASSWORD, "OMC_PUB", DB_PORT_NUM,
			SOCKET_NAME, FLAGS) == NULL) {
		fprintf(stderr, "Cannot connect to MySQL!!\n");		
		Print("[ERR][insertSeriousAlarmLog]:Fail to connect OMC_PUB");
		sleep(2);
	}
		
	sprintf(sqlstr,"INSERT INTO OMC_PUB.sysAlarmLog (sysTypeNo,sysNo,subSysNo,compCode,alarmCode,alarmTime) VALUES (0,%d,0,%d,%d,CURRENT_TIMESTAMP)",
		omcSysNo,compCode,alarmCode);
		
	if (mysql_query(alarmConn, sqlstr) != 0)
	{
		Print("[ERR][insertSeriousAlarmLog]:%s",sqlstr);
	}
	
	mysql_close(alarmConn);
}

/*	setup DB connection with both omc DB server */
void print_mysql_err(MYSQL * myconn)
{
	int errorNo = 0;

	errorNo = mysql_errno(myconn);
	if(errorNo > 0) 
	{
		fprintf(stderr, "\n Error number:%d", mysql_errno(myconn));
		fprintf(stderr, "\n Description: %s", mysql_error(myconn));
	}
}

/*	setup DB connection with both omc DB server */
MYSQL *mysql_conn(char *hostname, char *db_name)
{
	MYSQL *myconn;
	
	/*Initialize the conn point */
	while ((myconn = mysql_init(NULL)) == NULL) {
		fprintf(stderr, "Cannot initiate MySQL!!\n");
		print_mysql_err(myconn);
		
		if(CheckError(myconn))
		{
			Print("Host:%s",hostname);
			Print("DB  :%s",db_name);
			PrintError(myconn);
		}
		
		sleep(2);
	}

	while (mysql_real_connect
		   (myconn, hostname, USER_NAME, PASSWORD, db_name, DB_PORT_NUM,
			SOCKET_NAME, FLAGS) == NULL) {
		fprintf(stderr, "Cannot connect to MySQL!!\n");
		print_mysql_err(myconn);
		
		if(CheckError(myconn))
		{
			Print("Host:%s",hostname);
			Print("DB  :%s",db_name);
			PrintError(myconn);
		}
		
		sleep(2);
	}
	return myconn;
}


/*	mysql get query result*/
MYSQL_RES *mysql_getres(MYSQL * conn, char *strsql)
{
	MYSQL_RES *temp_res_set;
		
	if (mysql_query(conn, strsql) != 0) {
#if MYSQL_DEBUG
		fprintf(stderr, "\nSQL=%s", strsql);
#endif
		//print_mysql_err(conn);
		
		if(CheckError(conn))
		{
			PrintTime();
			PrintSQL(strsql);
			PrintError(conn);
			PrintEndDash();
		}
	} else {
		if ((temp_res_set = mysql_store_result(conn)) == NULL) {
			fprintf(stderr, "\n mysql store result error");
			//print_mysql_err(conn);
			
			if(CheckError(conn))
			{
				PrintTime();
				PrintSQL(strsql);
				PrintError(conn);
				PrintEndDash();
			}
			
		} else {
#if MYSQL_DEBUG
			fprintf(stderr, "\nSQL=%s \n", strsql);
#endif
			return temp_res_set;
		}
	}
	return NULL;
}

/*	Only execute query ,no result*/
int mysql_getnores(MYSQL * conn, char *strsql)
{
	long affected_rows;

	if (mysql_query(conn, strsql) != 0) {
#if MYSQL_DEBUG
		fprintf(stderr, "\nSQL=%s \n", strsql);
#endif
		//print_mysql_err(conn);
		
		if(CheckError(conn))
		{
			PrintTime();
			PrintSQL(strsql);
			PrintError(conn);
			PrintEndDash();
		}
		return -1;
	} else {
		//2008-9-16,modify the <= to <
		if ((affected_rows = mysql_affected_rows(conn)) < 0) {
#if MYSQL_DEBUG
			fprintf(stderr, "\n mysql query affected zero row !");
			fprintf(stderr, "\nSQL=%s \n", strsql);
#endif
			//print_mysql_err(conn);
			
			if(CheckError(conn))
			{
				PrintTime();
				PrintSQL(strsql);
				PrintError(conn);
				PrintEndDash();
			}

			return -1;
		}
#if MYSQL_DEBUG
		fprintf(stderr, "\nSQL=%s \n", strsql);
		fprintf(stderr, "\n mysql query affected %ld row !",
				affected_rows);
#endif
	}
	return 0;
}

/*by hewd 2003-04-22*/
int mysql_tblCpy(MYSQL * conn, const char *dstName, const char *srcName)
{
	char *tmpStr;
	//10240 13312
	char tmpSql[13312*2] = "/0";
	MYSQL_RES *tmpResultSet;
	MYSQL_ROW tmpRow;

	sprintf(tmpSql, "SHOW CREATE TABLE %s", srcName);
	tmpResultSet = mysql_getres(conn, tmpSql);

	if (tmpResultSet == NULL) {
		return (-1);
	} else if (mysql_num_rows(tmpResultSet) == 0) {
		mysql_free_result(tmpResultSet);
		return (-1);
	}

	tmpRow = mysql_fetch_row(tmpResultSet);
	//printf("\ncreate SQL=%s",tmpRow[1]);

	if (strlen(tmpRow[1]) >= 13312*2) {
		mysql_free_result(tmpResultSet);
		return (-1);
	}

	tmpStr = strchr(tmpRow[1], '(');
	//printf("\ntmpStr=%s",tmpStr);

	sprintf(tmpSql, "CREATE TABLE IF NOT EXISTS %s %s", dstName, tmpStr);

	if (mysql_query(conn, tmpSql) != 0) {
#if MYSQL_DEBUG
		fprintf(stderr, "\nSQL=%s \n", tmpSql);
#endif
		print_mysql_err(conn);
		mysql_free_result(tmpResultSet);
		return (-1);
	} else {
		mysql_free_result(tmpResultSet);
		return (0);
	}
}

void CheckMysqlConnect(MYSQL ** conn)
{
	if(mysql_ping(*conn))
	{
		mysql_close(*conn);
		*conn = (MYSQL *) mysql_conn(HOST_NAME, "mysql");
		if(*conn == NULL)
		{
			*conn = (MYSQL *) mysql_conn(HOST_NAME, "mysql");
		}
	}
}

#define EXIT_LOG_FILE "/usr/local/omc/log/exit_code.log"
void exitLog(const char *fmt, ...)
{
	FILE *fp;
	char buf[8096];
	char logDate[64];
	va_list args;
	long l_time;
	struct tm *t;
	
	fp=fopen(EXIT_LOG_FILE,"a+");
	if(fp == NULL)
		return;
	
	l_time=time(NULL);
	t=localtime(&l_time);
	sprintf(logDate,"\n%04d-%02d-%02d %02d:%02d:%02d \t",t->tm_year+1900,t->tm_mon+1,t->tm_mday,t->tm_hour,t->tm_min,t->tm_sec);
	va_start(args,fmt);
	vsprintf(buf,fmt,args);
	fputs(logDate,fp);
	fputs(buf,fp);
	fflush(fp);
	va_end(args);
	fclose(fp);
	return;
}

/**********************************
Write log to file MySQL********.log
**********************************/


void Print(const char *fmt,...)
{
	char logFile[64];
	FILE *fp;
	time_t l_time;
	va_list ap;
	char buf[81920];
	struct tm *t;
	
	l_time=time(NULL);
	t=localtime(&l_time);
	sprintf(logFile,"/usr/local/omc/log/MySQL%04d%02d%02d.log",t->tm_year+1900,t->tm_mon+1,t->tm_mday);
	fp=fopen(logFile,"a");
	if(fp!=NULL)
	{
		
		va_start(ap,fmt);
		vsprintf(buf,fmt,ap);
		fputs(buf,fp);
		fputs("\n",fp);
		fflush(fp);
		va_end(ap);
		fclose(fp);
	}
}

void PrintTime()
{
	time_t l_time;
	struct tm *t;
	
	l_time=time(NULL);
	t=localtime(&l_time);
	Print("--------------- %02d:%02d:%02d ---------------",t->tm_hour,t->tm_min,t->tm_sec);
}

void PrintEndDash()
{
	Print("----------------------------------------");
}

void PrintSQL(char *sqlstr)
{
	Print("SQL :%s",sqlstr);
}

void PrintError(MYSQL * myconn)
{
	Print("Err : %d",mysql_errno(myconn));
	Print("Desc: %s",mysql_error(myconn));
}

int CheckError(MYSQL * myconn)
{
	int errorNo=0;
	errorNo=mysql_errno(myconn);
	if(errorNo > 0)
	{
		switch(errorNo)
		{
		//Disk space full,compCode 2,alarmCode 1
		case 1021:
			insertSeriousAlarmLog(2,1);
			break;
		//Fail to write file,compCode 2,alarmCode 2
		case 1026:
			insertSeriousAlarmLog(2,2);
			break;
		//Table is full,compCode 2,alarmCode 3
		case 1114:	
			insertSeriousAlarmLog(2,3);
			break;
		//Table has been remarked as crashed,compCode 2,alarmCode 4
		case 1194:
			insertSeriousAlarmLog(2,4);
			break;
		//Table crashed and repair failed,compCode 2,alarmCode 5
		case 1195:
			insertSeriousAlarmLog(2,5);
			break;
		//DB crashed or not exist,compCode 2,alarmCode 6
		case 1244:
			insertSeriousAlarmLog(2,6);
			break;
		default:
			break;
		}
	}
	return errorNo;
}


