/*
FILE
	$Id: import.c 6 2005-11-24 00:02:59Z ggw $
	import.c
PURPOSE
	Import from old ism|2 msql tables mail and customer related
	data into mysqlSendmail tables.
LEGAL
	(C) Gary Wallis, 2002.
*/

#include "mysqlrad.h"
#include "local.h"

#include <msql.h>

int msqlConnectDb(void);
int msqlsock=0;
char dbip_msql[100]={""};
char dbname_msql[100]={"ism"};

void ConnectDb(void);

MYSQL mysql;
void NewClient(unsigned uCustId);
char *TextAreaSave(char *cField);
void stripwhitespace(char *cTargetEmail);

int main(int argc, char *argv[])
{
	m_result *res;
	m_row field;
	register int i;
	time_t clock;
	char query[8192];
	FILE *fp;
	unsigned uCustId=0;
	
	time(&clock);
	
	msqlsock=msqlConnectDb();
	ConnectDb();
	
	/////////////////////////////////////////	
	printf("Start import from login to tUser\n");
	sprintf(query,"SELECT custid,login,status FROM login WHERE status=0 OR status=1");
	i=msqlQuery(msqlsock,query);
	if(msqlErrMsg[0])
		fprintf(stderr,"%s\n",msqlErrMsg);

	if(!(fp=fopen("/etc/shadow","r")))
	{
		fprintf(stderr,"%s\n",msqlErrMsg);
		exit(1);
	}

	if(i)
	{
		char cPasswd[16];
		char cMatch[100];
		char *cp;
		unsigned uStatus=0;


		sprintf(query,"DELETE FROM tUser");
		mysql_query(&mysql,query);
		if(mysql_errno(&mysql)) 
		{
			fprintf(stderr,"%s\n",mysql_error(&mysql));
			exit(1);
		}

		res=msqlStoreResult();
		while((field=msqlFetchRow(res)))
		{
			//Very slow...
			cPasswd[0]=0;
			sprintf(cMatch,"%s:",field[1]);
			rewind(fp);
			while(fgets(query,512,fp))
			{
				if((cp=strstr(query,cMatch)))
				{
					strncpy(cPasswd,cp+strlen(cMatch),13);
					cPasswd[13]=0;
					break;
				}
			}

			sscanf(field[2],"%u",&uStatus);

sprintf(query,"INSERT INTO tUser SET  cLogin='%.63s', cPasswd='%.15s', uServer=1, uHDQuota=1, uTrafficQuota=1, uStatus=%u, uOwner=%.5s, uCreatedBy=1, uCreatedDate=%lu",
					field[1]	
					,cPasswd
					,uStatus+1
					,field[0]
					,(long unsigned)clock);

			mysql_query(&mysql,query);
			if(mysql_errno(&mysql)) 
			{
				fprintf(stderr,"%s\n",mysql_error(&mysql));
				exit(1);
			}

			printf("uOwner:%s cLogin:%s uStatus:%u cPasswd:%s\n",
					field[0],
					field[1],
					uStatus+1,
					cPasswd);

			sscanf(field[0],"%u",&uCustId);
			NewClient(uCustId);

		}
		msqlFreeResult(res);

	}
	fclose(fp);
	printf("End login to tUser\n\n");


	/////////////////////////////////////////	
	printf("Load from tAccess to tDomain\n");
	sprintf(query,"SELECT cDomainIPEtc,uCustId FROM tAccess WHERE uInCW=1");
	i=msqlQuery(msqlsock,query);
	if(msqlErrMsg[0])
		fprintf(stderr,"%s\n",msqlErrMsg);
	if(i)
	{
		time_t clock;


		sprintf(query,"DELETE FROM tDomain");
		mysql_query(&mysql,query);
		if(mysql_errno(&mysql)) 
		{
			fprintf(stderr,"%s\n",mysql_error(&mysql));
			exit(1);
		}

        	time(&clock);

		res=msqlStoreResult();
		while((field=msqlFetchRow(res)))
		{

			sscanf(field[0],"%u",&uCustId);
sprintf(query,"INSERT INTO tDomain SET cDomain='%s', uServer=1, uStatus=1, uOwner=%u, uCreatedBy=1, uCreatedDate=%lu",
			field[0]
			,uCustId
			,(long unsigned)clock);

			mysql_query(&mysql,query);
			if(mysql_errno(&mysql)) 
			{
				fprintf(stderr,"%s\n",mysql_error(&mysql));
				exit(1);
			}

			printf("cDomain:%s uCustId:%u\n",field[0],uCustId);

			NewClient(uCustId);
		}
		msqlFreeResult(res);
	}
	printf("End tAccess to tDomain\n\n");

	//////////////////////////////////////////////
	printf("Load from msql tAccess to tAccess\n");
	sprintf(query,"SELECT tAccess.cDomainIPEtc,tAccess.uCustId,tAccessAtr.cAtrText FROM tAccess,tAccessAtr WHERE tAccess.uAccessAtr=tAccessAtr.uAccessAtr AND tAccess.uInCW=0");
	i=msqlQuery(msqlsock,query);
	if(msqlErrMsg[0])
		fprintf(stderr,"%s\n",msqlErrMsg);
	if(i)
	{
		time_t clock;


		sprintf(query,"DELETE FROM tAccess");
		mysql_query(&mysql,query);
		if(mysql_errno(&mysql)) 
		{
			fprintf(stderr,"%s\n",mysql_error(&mysql));
			exit(1);
		}

        	time(&clock);

		res=msqlStoreResult();
		while((field=msqlFetchRow(res)))
		{

			sscanf(field[1],"%u",&uCustId);
sprintf(query,"INSERT INTO tAccess SET cDomainIP='%s', uServer=1, cRelayAttr='%s', uOwner=%u, uCreatedBy=1, uCreatedDate=%lu",
			field[0]
			,field[2]
			,uCustId
			,(long unsigned)clock);

			mysql_query(&mysql,query);
			if(mysql_errno(&mysql)) 
			{
				fprintf(stderr,"%s\n",mysql_error(&mysql));
				exit(1);
			}
			printf("cDomainIP:%s cRelayAttr:%s uCustId:%u\n"
					,field[0],field[2],uCustId);
			NewClient(uCustId);
		}
		msqlFreeResult(res);
		
	}
	printf("End msql tAccess to tAccess\n\n");


	///////////////////////////////////////////////
	printf("Load from tVut to tVUT,tVUTEntries\n");
	sprintf(query,"SELECT cDomain,cDefinitions,uStatus,uCustId FROM tVut");
	i=msqlQuery(msqlsock,query);
	if(msqlErrMsg[0])
		fprintf(stderr,"%s\n",msqlErrMsg);
	if(i)
	{
		time_t clock;
		char *cp;
		unsigned uVUT=0;

		sprintf(query,"DELETE FROM tVUT");
		mysql_query(&mysql,query);
		if(mysql_errno(&mysql)) 
		{
			fprintf(stderr,"%s\n",mysql_error(&mysql));
			exit(1);
		}
		sprintf(query,"DELETE FROM tVUTEntries");
		mysql_query(&mysql,query);
		if(mysql_errno(&mysql)) 
		{
			fprintf(stderr,"%s\n",mysql_error(&mysql));
			exit(1);
		}

        	time(&clock);

		res=msqlStoreResult();
		while((field=msqlFetchRow(res)))
		{

			sscanf(field[3],"%u",&uCustId);
sprintf(query,"INSERT INTO tVUT SET cDomain='%s', uStatus=%s, uOwner=%u, uCreatedBy=1, uCreatedDate=%lu, uServer=1",
		field[0] ,field[2],uCustId ,(long unsigned)clock);

			mysql_query(&mysql,query);
			if(mysql_errno(&mysql)) 
			{
				fprintf(stderr,"%s\n",mysql_error(&mysql));
				exit(1);
			}
			
			
			printf("cDomain:%s uStatus:%s uCustId:%u\n"
					,field[0],field[2],uCustId);
			printf("cDefinitions:\n%s\n",field[1]);
			
		
			//Get insert row id
			uVUT=mysql_insert_id(&mysql);

			//insert tVUTEntries by parsing cDefinitions by line
			cp=field[1];
			for(i=0;field[1][i];i++)
			{
				if(field[1][i]=='\n' 
						|| field[1][i]=='\r' 
						|| field[1][i+1]==0)
				{
					char *cp2;
					char cLine[1024]={""};
					char cVirtualEmail[32]={""};
					char cTargetEmail[100]={""};
					
					if(field[1][i+1]!=0)
						field[1][i]=0;
					strcpy(cLine,cp);	
					cp=field[1]+i+1;
					
					if((cp2=strchr(cLine,'@')))
					{
						char *cp3;

						*cp2=0;
						sprintf(cVirtualEmail,
							"%.31s",cLine);
						if((cp3=strchr(cp2+1,' ')))
							sprintf(cTargetEmail,
								"%.99s",cp3+1);
					
sprintf(query,"INSERT INTO tVUTEntries SET  uVUT=%u, cVirtualEmail='%s', cTargetEmail='%s', uServer=1, uOwner=%u, uCreatedBy=1, uCreatedDate=%lu",
			uVUT
			,TextAreaSave(cVirtualEmail)
			,TextAreaSave(cTargetEmail)
			,uCustId
			,(long unsigned)clock);
					mysql_query(&mysql,query);
					if(mysql_errno(&mysql)) 
					{
						fprintf(stderr,"%s\n",
								mysql_error(&mysql));
						exit(1);
					}

					printf("cVirtualEmail:%s\n",
							cVirtualEmail);
					printf("cTargetEmail:%s\n\n",
							cTargetEmail);
					}
				}
			}
			

			NewClient(uCustId);
		}
		msqlFreeResult(res);
	}	
	printf("End from tVut to tVUT,tVUTEntries\n\n");


	///////////////////////////////////////
	printf("Load from tNASPool to tDUL\n");
	sprintf(query,"SELECT uCustId,cPool,uStatus FROM tNASPool");
	i=msqlQuery(msqlsock,query);
	if(msqlErrMsg[0])
		fprintf(stderr,"%s\n",msqlErrMsg);
	if(i)
	{
		time_t clock;


		sprintf(query,"DELETE FROM tDUL");
		mysql_query(&mysql,query);
		if(mysql_errno(&mysql)) 
		{
			fprintf(stderr,"%s\n",mysql_error(&mysql));
			exit(1);
		}

        	time(&clock);

		res=msqlStoreResult();
		while((field=msqlFetchRow(res)))
		{

			sscanf(field[0],"%u",&uCustId);
sprintf(query,"INSERT INTO tDUL SET cRangeList='%s', uStatus=%s, uProviderID=%u, uOwner=%u, uCreatedBy=1, uCreatedDate=%lu, uServer=1",
			TextAreaSave(field[1])
			,field[2]
			,uCustId
			,uCustId
			,(long unsigned)clock);

			mysql_query(&mysql,query);
			if(mysql_errno(&mysql)) 
			{
				fprintf(stderr,"%s\n",mysql_error(&mysql));
				exit(1);
			}
			printf("uCustId:%u uStatus:%s cRangeList:%.50s...\n"
					,uCustId,field[2],
					TextAreaSave(field[1]));
			NewClient(uCustId);
		}
		msqlFreeResult(res);
		
	}
	printf("End from tNASPool to tDUL\n\n");


	///////////////////////////////////////////////
	printf("Load from /etc/aliases to tAlias\n");
	if(!(fp=fopen("/etc/aliases","r")))
	{
		fprintf(stderr,"%s\n",msqlErrMsg);
		exit(1);
	}
	else
	{
		time_t clock;
		char cUser[33];
		char cTargetEmail[256];
		char *cp;

		sprintf(query,"DELETE FROM tAlias");
		mysql_query(&mysql,query);
		if(mysql_errno(&mysql)) 
		{
			fprintf(stderr,"%s\n",mysql_error(&mysql));
			exit(1);
		}

        	time(&clock);

		while(fgets(query,512,fp))
		{
			if(query[0]=='#') continue;
			
			if((cp=strchr(query,':')))
			{
				*cp=0;
				strcpy(cUser,query);
				strcpy(cTargetEmail,cp+1);
				//cTargetEmail[strlen(cTargetEmail)-1]=0;
				stripwhitespace(cTargetEmail);

sprintf(query,"INSERT INTO tAlias SET cUser='%s', cTargetEmail='%s', uServer=1,uOwner=1, uCreatedBy=1, uCreatedDate=%lu",
				TextAreaSave(cUser)
				,TextAreaSave(cTargetEmail)
				,(long unsigned)clock);

				mysql_query(&mysql,query);
				if(mysql_errno(&mysql)) 
				{
					fprintf(stderr,"%s\n",
						mysql_error(&mysql));
				}

				printf("cUser:'%s' cTargetEmail:'%s'\n",
					cUser,cTargetEmail);
			}
		}
		fclose(fp);
	}
	printf("End from /etc/aliases to tAliases\n\n");

	return(0);

}//int main()


int msqlConnectDb(void)
{
	
	if(!msqlsock)
	{
		if(dbip_msql[0])
			msqlsock=msqlConnect(dbip_msql);
		else
			msqlsock=msqlConnect(NULL);
	
		if(!msqlsock)
		{
			fprintf(stderr,"Error: msql Database Down\n");
			exit(1);
		}
	}
	else
	{
		return msqlsock;
	}

	msqlSelectDB(msqlsock,dbname_msql);
	if(msqlErrMsg[0])
	{
		fprintf(stderr,"%s\n",msqlErrMsg);
		exit(1);
	}

	return msqlsock;
						
}//end of msqlConnectDb()


void ConnectDb(void)
{
        mysql_init(&mysql);
        if (!mysql_real_connect(&mysql,NULL,DBLOGIN,DBPASSWD,DBNAME,0,NULL,0))
        {
                fprintf(stderr,"Database server unavailable. Did you run mysqlSendmail.cgi Initialize &lt;mysqlpwd&gt;?");
		exit(1);
        }

}//end of ConnectDb()


void NewClient(unsigned uCustId)
{
	m_result *res;
	m_row field;
	time_t clock;
	char query[4096];

	if(!uCustId) return;

sprintf(query,"SELECT name,company,address,city,state,zip,phone,email FROM client WHERE custid=%u",uCustId);

	msqlQuery(msqlsock,query);
	if(msqlErrMsg[0])
	{
		fprintf(stderr,"%s\n",msqlErrMsg);
		exit(1);
	}
	res=msqlStoreResult();
	if((field=msqlFetchRow(res)))
	{
		char cFirstName[100];
		char cLastName[100];
		char *cp;
		time(&clock);

		strncpy(cFirstName,field[0],99);
		cFirstName[99]=0;
		if((cp=strchr(cFirstName,' ')))
		{
			*cp=0;
			strncpy(cLastName,cp+1,99);
			cLastName[99]=0;
		}

	sprintf(query,"INSERT INTO tClient SET  uClient=%u, cLabel='%s', uMaxUsers=%u, cFirstName='%s', cLastName='%s', cCompanyName='%s', cEmail='%s', cAddr1='%s', cCity='%s', cState='%s', cZip='%s', cCountry='%s', cTelephone='%s', uOwner=%u, uCreatedBy=%u, uCreatedDate=%lu",
			uCustId
			,field[0]
			,5//uMaxUsers
			,cFirstName
			,cLastName
			,field[1]//cCompanyName
			,field[7]//cEmail
			,field[2]//cAddr1
			,field[3]//TextAreaSave(cCity)
			,field[4]//TextAreaSave(cState)
			,field[5]//TextAreaSave(cZip)
			,"USA"//TextAreaSave(cCountry)
			,field[6]//TextAreaSave(cTelephone)
			,1//uOwner
			,1//uCreatedBy
			,(long unsigned)clock);

		mysql_query(&mysql,query);
		if(mysql_errno(&mysql)) 
		{
			fprintf(stderr,"%s\n",
					mysql_error(&mysql));
		}
	}

	msqlFreeResult(res);

}//void NewClient()


char *TextAreaSave(char *cField)
{
	register unsigned int i=0,j=0,uNum=0,uCtrlM=0;
	char *cCopy=NULL;

	for(i=0;cField[i];i++)
	{
		if(cField[i]=='\'' || cField[i]=='\\') uNum++;
		if(cField[i]=='\r') uCtrlM++;
	}
	if(!uNum && !uCtrlM) return(cField);

	if(uNum)
		cCopy=(char *)malloc( ( (strlen(cField)) + (uNum*2) + 1 ));
	else
		cCopy=cField;

	if(!cCopy) 
	{
		fprintf(stderr,"TextAreaInput() malloc error\n");
		exit(1);
	}

	i=0;
	while(cField[i])
	{
		//Escape single quotes execpt when saving tabs
		if( cField[i]=='\'' )
		{
			cCopy[j++]='\\';
			cCopy[j++]='\'';
		}
		//Escape escape except when saving tabs with escape. (He he ?)
		else if( cField[i]=='\\' && cField[i+1]!='t')
		{
			cCopy[j++]='\\';
			cCopy[j++]='\\';
		}
		
		//Remove nasty ctrl-m's. fsck /u Bill!
		else if(cField[i]!='\r')
		{
			cCopy[j++]=cField[i];
		}
		i++;
	}

	cCopy[j]=0;
	return(cCopy);

}//char *TextAreaSave(char *cField)


void stripwhitespace(char *cTargetEmail)
{
	register int i,j=0;
	char cTargetEmail2[1024];

	for(i=0;cTargetEmail[i]&&i<1023;i++)
	{
		if(!isspace(cTargetEmail[i]))
			cTargetEmail2[j++]=cTargetEmail[i];
	}

	cTargetEmail2[j]=0;
	strcpy(cTargetEmail,cTargetEmail2);

}//void stripwhitespace(char *cTargetEmail)

