/*************************************************
File name:	initParaConf.c
Author: 	Cui Ticun
Version:	9.00.00 
Date:  		2007-7-1
Description:This file init every modules' paraConf table from MIB files,
			It includes the function 'int initDbFromMib()',which is called by paraCommInit.
			It calls snmp's functions:extern int init_mib();
									  extern struct tree *getLGCroot();
									  extern struct tree *get_tree(const int *oid, int oidlen, struct tree *subtree);
									  extern void close_mib();
									
History:               
No. 
Author  
Date    
Version   
Description
*************************************************/

#include "paraComm.h"

#define SYSTEM_TYPE 355

static MYSQL *dbConn;
char indexsQuery[10240];
extern FILE *paraCommLog;

void preOrderMibTree(struct tree *mibTree);
void orderEnums(struct enum_list *enums,char *str);
void orderIndexes(struct index_list *indexes,char *str);
//BYTE str2oid(char *str, DWORD * array, BYTE max);
BYTE str2oid(char *str, int * array, BYTE max);

#define MAX_MODULE_NUMBER 64
int global_mod_index;
//DWORD global_mod_oids[MAX_MODULE_NUMBER][32];
int global_mod_oids[MAX_MODULE_NUMBER][32];
int global_mod_systype[MAX_MODULE_NUMBER];
/*=
	{
		{1373,2,3,3,2,2},
		{1373,2,3,3,64,2}
	};
	
int global_mod_systype[global_mod_total]={320,355};
*/


/*************************************************
Function:        // initDbFromMib
Description:     // Get oid info from MIB file and init the paramConf tables.
Calls:           // extern int init_mib();extern struct tree *getLGCroot();extern struct get_tree;extern void close_mib();
Called By:       // paraCommInit();
Table Accessed:  // 
Table Updated:   // paramConf
Input:           // 
Output:          // 
Return:          // 1:OK,0:error
Others:          // 
*************************************************/
int initDbFromMib()
{
	//DWORD oidArr[32]={ 1373, 2, 3, 3, 2, 2 };
	struct tree *tmpLGCRoot;
	struct tree *mibTree;
	int i,oidlen;
	char tmpSql[10240];
	int mod_total;
	MYSQL_RES *res=NULL;
	MYSQL_ROW rows;
	
	
	//init db connect
	dbConn = mysql_conn(HOSTNAME, PUB_DB);
	if (dbConn == NULL) {
		omcLog(paraCommLog,"[ERR][initDbFromMib]:mysql connect OMC_PUB");
		return (0);
	}
	
	
	
	//memset(global_mod_oids,0,sizeof(DWORD)*32*MAX_MODULE_NUMBER);
    memset(global_mod_oids,0,sizeof(int)*32*MAX_MODULE_NUMBER);
	sprintf(tmpSql, "SELECT sysTypeNo,entryOid FROM sysMibConf WHERE isEnable = '1' ");

	res = (MYSQL_RES *) mysql_getres(dbConn, tmpSql);
	
	if(res == NULL)
	{
		omcLog(paraCommLog, " Database may be stopped,when initDbFromMib");
		exit(1);
	}
	
	global_mod_index=0;
	mod_total=0;
	while ((rows = mysql_fetch_row(res))) 
	{
		if(mod_total >= MAX_MODULE_NUMBER)
		{
			omcLog(paraCommLog,"The number pf mib files is too large");
			break;
		}
		
		//mod_oids[mod_total]
		global_mod_systype[mod_total]=atoi(rows[0]);
		oidlen=str2oid(rows[1],global_mod_oids[mod_total],20);
		/*
		for(i=0;i<oidlen+1;i++)
			printf("%d.",global_mod_oids[mod_total][i]);
		printf("\n");
		*/
		mod_total++;
	}
	
	mysql_free_result(res);
	
	init_mib();
	tmpLGCRoot=getLGCroot();

	for(global_mod_index=0;global_mod_index<mod_total;global_mod_index++)
	{
		sprintf(tmpSql,"DELETE FROM OBJ_%d.paramConf",global_mod_systype[global_mod_index]);
		mysql_getnores(dbConn,tmpSql);

		mibTree=get_tree((int*)global_mod_oids[global_mod_index],6,tmpLGCRoot);
		
		if(mibTree==tmpLGCRoot || mibTree->subid != global_mod_oids[global_mod_index][5]){	
			printf("Cannot find the OID in MIB File:");
			for(i=0;i<6;i++){
				printf("%ld.",global_mod_oids[global_mod_index][i]);
			}
			printf("\n");
			exit(1);
		}
		// indexsQuery[0]=0;
		memset(&indexsQuery[0], 0x00, sizeof(indexsQuery));
		preOrderMibTree(mibTree);
		strcat(indexsQuery,")");
		
		//Modify Index's access from MIB_ACCESS_READWRITE to MIB_ACCESS_CREATE
		if(strlen(indexsQuery)>3)
		{
			sprintf(tmpSql,"UPDATE OBJ_%d.paramConf SET maxAccess='%d' WHERE maxAccess='%d' AND %s",
						global_mod_systype[global_mod_index],MIB_ACCESS_CREATE,MIB_ACCESS_READWRITE,indexsQuery);
			mysql_getnores(dbConn,tmpSql);
		}
		
		sprintf(tmpSql,"UPDATE OBJ_%d.paramConf SET operType='%d' WHERE name_2 LIKE '%%CreateTimeStamp'",
						global_mod_systype[global_mod_index],DO_NOT_DISPLAY);
		//printf("tmpSql=%s\n",tmpSql);
		mysql_getnores(dbConn,tmpSql);
		
		sprintf(tmpSql,"UPDATE OBJ_%d.paramConf SET operType='%d' WHERE name_2 LIKE '%%AdministrationState'",
						global_mod_systype[global_mod_index],LABEL);
		//printf("tmpSql=%s\n",tmpSql);
		mysql_getnores(dbConn,tmpSql);
	}
	close_mib();
	
	return 1;
}

/*************************************************
Function:        // preOrderBinTree
Description:     // Preorder traversal the mibtree(bintree) 
Calls:           // 
Called By:       // initDbFromMib
Table Accessed:  // 
Table Updated:   // 
Input:           // struct tree *mibTree
Output:          // 
Return:          // 
Others:          // 
*************************************************/
void preOrderMibTree(struct tree *mibTree)
{
	int i;
	//16384
	char tmpStr[40960];
	char tmpStr1[20480];	
	char tmpSql[40960];
	
	char tmpEnumsList[1024];
	char tmpIndexesList[1024];
	char *onePart;
	char *anotherPart;
	int tmpLen;
	char *tempc;
	char name[128];
	char desc[2048];
	
	if(mibTree){
		//printf("%s\n",mibTree->label);
		sprintf(tmpSql,"REPLACE INTO OBJ_%d.paramConf SET ",global_mod_systype[global_mod_index]);
		// name	
		sprintf(tmpStr,"name_1='%s',name_2='%s'",mibTree->label,mibTree->label);
		strcat(tmpSql,tmpStr);
		
		
		sprintf(name,"none");	
		if(mibTree->description && strstr(mibTree->description,"Name:")!=NULL)
		{
			sprintf(desc,mibTree->description);
			tempc=strstr(desc,"\n");
			if(tempc != NULL)
				*tempc=0;
			tempc=strstr(desc,"Name:");
			if(tempc == NULL)
			{
				sprintf(name,"none");
			}
			else
			{
				sprintf(name,"%s",tempc+5);
				//printf("%s\n",name);
			}
		}

	
		//Description
		if(mibTree->indexes){
			if(mibTree->description && !strstr(mibTree->description,"Description."))
				sprintf(tmpStr,",desc_1='Table Parameter, %s',desc_2='Table Parameter, %s'",mibTree->description,mibTree->description);
			else
			{
				if(strcmp(name,"none"))
					sprintf(tmpStr,",desc_1='Table Parameter, level:1, Name:%s',desc_2='Table Parameter, level:1, Name:%s'",name,name);
				else
					sprintf(tmpStr,",desc_1='Table Parameter, level:1',desc_2='Table Parameter, level:1'");
			}
			strcat(tmpSql,tmpStr);
		}else{
			char tmpdesc[4096];
			tmpdesc[0]=0;
			if(mibTree->description)
			{
				if(strstr(mibTree->description,"Hidden Flag:Yes"))
				{
					strcat(tmpdesc,"Hidden Parameter;");
				}
				else if(strstr(mibTree->description,"Key Parameter:Yes"))
				{
					strcat(tmpdesc,"Key Parameter;");
				}
				else if(strstr(mibTree->description,"PASSWORD:Visible"))
				{
					strcat(tmpdesc,"PASSWORD:Visible;");
				}
				else if(strstr(mibTree->description,"PASSWORD:Invisible"))
				{
					strcat(tmpdesc,"PASSWORD:Invisible;");
				}
								
				if(strcmp(name,"none"))
				{
					sprintf(tmpStr,"Name:%s;",name);
					strcat(tmpdesc,tmpStr);
				}
								
				if((tempc=strstr(mibTree->description,"RelationPoint:")))
				{
					char *tempc1=NULL;

					tempc1=strstr(tempc,"\n");
					if(tempc1 != NULL)
						*tempc1=0;
					sprintf(tmpStr,"%s;",tempc);
					strcat(tmpdesc,tmpStr);
				}
				
			}
			
			if(strlen(tmpdesc)>0)
			{
				sprintf(tmpStr,",desc_1='%s',desc_2='%s'",tmpdesc,tmpdesc);
				strcat(tmpSql,tmpStr);
			}
			/*
			
			if(mibTree->description&&strstr(mibTree->description,"Hidden Flag:Yes"))
			{
				sprintf(tmpStr,",desc_1='Hidden Parameter',desc_2='Hidden Parameter'");
				strcat(tmpSql,tmpStr);
			}
			else if(mibTree->description&&
				strstr(mibTree->description,"Key Parameter:Yes")){
				if(strcmp(name,"none"))
					sprintf(tmpStr,",desc_1='Key Parameter, Name:%s',desc_2='Key Parameter, Name:%s'",name,name);
				else
					sprintf(tmpStr,",desc_1='Key Parameter',desc_2='Key Parameter'");
				strcat(tmpSql,tmpStr);
			}
			else if(strcmp(name,"none"))
			{
				sprintf(tmpStr,",desc_1='Name:%s',desc_2='Name:%s'",name,name);
				strcat(tmpSql,tmpStr);
			}
			*/
		}
			
		//OPAQUE DECODE RULE:
		if(mibTree->description){	
			if((onePart=strstr(mibTree->description,"OPAQUE DECODE RULE:"))){

				strsep(&(onePart),":");
				if((anotherPart=strstr(mibTree->description,"Remark:")))
					strncpy(tmpStr1,onePart,(anotherPart-onePart));
				else
					strcpy(tmpStr1,onePart);	
				sprintf(tmpStr,",setTemplate_1='%s',setTemplate_2='%s'",tmpStr1,tmpStr1);
				strcat(tmpSql,tmpStr);
			}		
		}

		if(mibTree->description){	
			//Note
			if((onePart=strstr(mibTree->description,"Remark:"))){
				strsep(&(onePart),":");
				if(onePart){
					sprintf(tmpStr,",note_1=\"%s\",note_2=\"%s\"",onePart,onePart);
					strcat(tmpSql,tmpStr);	
				}
			}
		}
		
		//Max Access
		sprintf(tmpStr,",maxAccess='%d'",mibTree->access);
		strcat(tmpSql,tmpStr);
				
		//operType
		if(mibTree->access==MIB_ACCESS_READONLY){
			sprintf(tmpStr,",operType='%d'",LABEL);
			strcat(tmpSql,tmpStr);
		}else if(mibTree->access==MIB_ACCESS_NOACCESS){
			sprintf(tmpStr,",operType='%d'",DO_NOT_DISPLAY);
			strcat(tmpSql,tmpStr);
		}else{
			if(mibTree->type==TYPE_INTEGER&&mibTree->enums){
				sprintf(tmpStr,",operType='%d'",PULLDOWN_MENU);
				strcat(tmpSql,tmpStr);
			}else{
				sprintf(tmpStr,",operType='%d'",TEXTBOX);
				strcat(tmpSql,tmpStr);
			}
		}
		
		//valueType		
		sprintf(tmpStr,",valueType='%d'",mibTree->type);
		strcat(tmpSql,tmpStr);
		
		//initValue
		if(mibTree->defaultValue){
			sprintf(tmpStr,",initValue='%s'",mibTree->defaultValue);
			strcat(tmpSql,tmpStr);
		}
		
		//minValue
		//maxValue
		if(mibTree->ranges){
			sprintf(tmpStr,",`minValue`='%d',`maxValue`='%d'",mibTree->ranges->low,mibTree->ranges->high);
			strcat(tmpSql,tmpStr);
		}
		
		//template
		if(mibTree->enums){
			tmpEnumsList[0]=0;
			orderEnums(mibTree->enums,tmpEnumsList);
			
			tmpLen=strlen(tmpEnumsList);
			tmpEnumsList[tmpLen-1]=0;
			
			sprintf(tmpStr,",setTemplate_1='%s',setTemplate_2='%s'",tmpEnumsList,tmpEnumsList);
			strcat(tmpSql,tmpStr);
		}else if(mibTree->indexes){
			tmpIndexesList[0]=0;
			orderIndexes(mibTree->indexes,tmpIndexesList);
			
			tmpLen=strlen(tmpIndexesList);
			tmpIndexesList[tmpLen-1]=0;
			
			sprintf(tmpStr,",setTemplate_1='%s',setTemplate_2='%s'",tmpIndexesList,tmpIndexesList);
			strcat(tmpSql,tmpStr);
		}
		
		//level_x	
		for(i=11;i<mibTree->oid_len;i++){
			sprintf(tmpStr,",level_%d=%d",i-10,mibTree->oid[i]);
			strcat(tmpSql,tmpStr);
		}	
				
		if(mysql_getnores(dbConn,tmpSql)<0){
			printf("\n%s\n",tmpSql); 
		}
		
		/*		
		for(i=0;i<mibTree->oid_len;i++){
			printf("%d.",mibTree->oid[i]);
		}
		printf("\n");
		*/
		preOrderMibTree(mibTree->child_list);
		preOrderMibTree(mibTree->next_peer);		
	}
	return;
}

/*************************************************
Function:        // orderEnums
Description:     // construct the list of enumerated integers to a string
Calls:           // 
Called By:       // preOrderMibTree
Table Accessed:  // 
Table Updated:   // 
Input:           // struct enum_list *enums,
Output:          // char *str
Return:          // 
Others:          // 
*************************************************/
void orderEnums(struct enum_list *enums,char *str)
{
	char tmpStr[64];
	if(enums){
		sprintf(tmpStr,"%s=%d;",enums->label,enums->value);
		strcat(str,tmpStr);
		orderEnums(enums->next,str);
	}
}

/*************************************************
Function:        // orderIndexes
Description:     // construct the list of enumerated indexes to a string
Calls:           // 
Called By:       // preOrderMibTree
Table Accessed:  // 
Table Updated:   // 
Input:           // struct index_list *indexes
Output:          // char *str
Return:          // 
Others:          // 
*************************************************/
void orderIndexes(struct index_list *indexes,char *str)
{
	char tmpStr[64];
	if(indexes){
		sprintf(tmpStr,"%s;",indexes->ilabel);
		strcat(str,tmpStr);
		if(strlen(indexsQuery)>0)
			sprintf(tmpStr," OR name_2='%s'",indexes->ilabel);
		else
			sprintf(tmpStr," (name_2='%s'",indexes->ilabel);
		strcat(indexsQuery,tmpStr);
		orderIndexes(indexes->next,str);
	}
}

//BYTE str2oid(char *str, DWORD * array, BYTE max)
BYTE str2oid(char *str, int * array, BYTE max)
{
	BYTE sub = 0;
	short len, i;
	char *pvar;
	len = strlen(str);
	pvar = str;
	for (i = 0; i < len && sub < max; i++) {
		if (str[i] == '.') {
			str[i] = '\0';
			if (strlen(pvar) == 0)
				continue;
			array[sub++] = atoi(pvar);
			pvar = str + i + 1;
		}
	}
	if (strlen(pvar) == 0)
		return sub;
	array[sub++] = atoi(pvar);
	return sub;
}
