// Standard Unix includes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <dotconf.h>
#include <mysql/mysql.h>

#include "log.h"
#include "config_file.h"
#include "global.h"
//#include "message.h"
#include "my_strings.h"
#include "sql_query.h"


MYSQL mysql,*sock;
void do_ze_mysql_connect(){
//	MYSQL_RES* res;
	mysql_init(&mysql);
	if (!(sock = mysql_real_connect(&mysql,igw_config.mysql_hostname,
				igw_config.mysql_user,igw_config.mysql_pass,igw_config.mysql_db,0,NULL,0))){
		fprintf(stderr,"Couldn't connect to mysql engine!\n%s\n\n",mysql_error(&mysql));
		exit(2);
	}
	return;
}

void testQuery(){
	char* dup;
	printf("Testting query\n");
	if(mysql_query(sock,"SELECT pop3_email FROM mailbox WHERE igw_login='zigo' AND pop3_server='gplhost.com' AND pop3_login='zigo@pplchat.com';")){
		fprintf(stderr,"Query: failed ! %s\n",mysql_error(sock));
		exit(2);
	}else{
		fprintf(stderr,"Query: success !\n");
	}
	dup = strdup("test");
	printf("duped: %s\n",dup);
}

void mysql_cleanUp(){
	LOG("Disconnect from MySQL.......");
	mysql_close(sock);
	LOG("done!\n");
}

// Does check for input stings size and if contains \ or ' (no db hack possible)
// This one is guessed by the 3 first in DB (table mailbox)
// NULL if not found
// @return: char* fetchmail_email_addr;
char* findRetrivedMailbox(char** igw_login,char* pop3_username,char* pop3_server){
	MYSQL_RES *res;
	MYSQL_ROW row;
	char* ret;
	char q[1024];
	int num_rows;

	if(strlen(pop3_server)+strlen(pop3_username) > 512){
		return NULL;
	}
	if(
		strstr(pop3_server,"'") || strstr(pop3_server,"\\") ||
		strstr(pop3_username,"'") || strstr(pop3_username,"\\")){
		return NULL;
	}
	sprintf(q,"SELECT igw_login,pop3_email FROM mailbox WHERE pop3_server='%s' AND pop3_login='%s';",
		pop3_server,pop3_username);
//	LOG("\"");
//	LOG(q);
//	LOG("\"")
//	LOG("\n");
	if(mysql_query(sock,q)){
		sprintf(q,"Query: \"%s\" failed ! %s\n",q,mysql_error(sock));
		return NULL;
	}
	if (!(res=mysql_store_result(sock))){
		fprintf(stderr,"Couldn't get result from %s\n",mysql_error(sock));
		return NULL;
	}
	num_rows = mysql_num_rows(res);
	if(num_rows != 1){
		mysql_free_result(res);
		return NULL;
	}
	row = mysql_fetch_row(res);
	if(row == NULL){
		fprintf(stderr,"Couldn't fetch row: %s\n",mysql_error(sock));
		mysql_free_result(res);
		return NULL;
	}
	*igw_login = strdup(row[0]);
	ret=strdup(row[1]);
	mysql_free_result(res);
//	printf("founded:%s\n",ret);
	return (ret);
}

char* isInWhitelist(char* igw_login,char* mailBoxname,char* from_user,char* from_domain){
	MYSQL_RES *res;
	int num_rows=0;
	char q[1024];

//	sprintf(q,"SELECT * FROM whitelist WHERE igw_login='%s' AND (mail_from_user='%s' OR mail_from_user='*') AND mail_from_domain='%s' AND mailbox='%s';",
//			igw_login,from_user,from_domain,mailBoxname);
	sprintf(q,"SELECT * FROM whitelist WHERE igw_login='%s' AND mailbox LIKE '%c%s%c' AND mail_from_domain='%s' AND (mail_from_user='%s' OR mail_from_user='*');",
			igw_login,'%',mailBoxname,'%',from_domain,from_user);
//	printf("Query: \"%s\"\n",q);
	if(mysql_query(sock,q)){
        	fprintf(stderr,"Query: \"%s\" failed ! %s\n",q,mysql_error(sock));
	}
	if (!(res=mysql_store_result(sock))){
		fprintf(stderr,"Couldn't get result from %s\n",mysql_error(sock));
		return NULL;
	}
	num_rows = mysql_num_rows(res);
//	printf("\nNUMROWS:%d\n",num_rows);
	mysql_free_result(res);
	if(num_rows < 1){
		return NULL;
	}
	return "founded";
}

char* isInTolist(char* igw_login,char* mailBoxname,char* addr){
	MYSQL_RES *res;
	int num_rows=0;
	char q[1024];

	sprintf(q,"SELECT * FROM whitelist WHERE igw_login='%s' AND mailbox LIKE '%c%s%c' AND mail_to='%s';",
			igw_login,'%',mailBoxname,'%',addr);
	if(mysql_query(sock,q)){
        	fprintf(stderr,"Query: \"%s\" failed ! %s\n",q,mysql_error(sock));
	}
	if (!(res=mysql_store_result(sock))){
		fprintf(stderr,"Couldn't get result from %s\n",mysql_error(sock));
		return NULL;
	}
	num_rows = mysql_num_rows(res);
//	printf("\nNUMROWS:%d\n",num_rows);
	mysql_free_result(res);
	if(num_rows < 1){
		return NULL;
	}
	return "founded";
}

void saveMessageToSql(char* random_val,char* igw_login,
	char* mailbox,char* message,char* subject,char* frombox){
	char* q;

	char* esc_subject;

	esc_subject = addSlashes(subject,strlen(subject));

	q = (char*)malloc(1024+strlen(random_val)+strlen(igw_login)+strlen(mailbox)+strlen(message)+strlen(subject)+strlen(frombox));
	sprintf(q,"INSERT INTO validate_url (date,time,random_val,igw_login,mailbox,message,subject,frombox)VALUES(CURDATE(),CURTIME(),'%s','%s','%s','%s','%s','%s');",
		random_val,igw_login,mailbox,message,esc_subject,frombox);
	if(mysql_query(sock,q)){
		fprintf(stderr,"Query: \"%s\" failed ! %s\n",q,mysql_error(sock));
		exit(1);
		return;
	}
	free(q);
}

char* getCustomBounceMessage(char* igw_login,char* mailbox){
	MYSQL_RES* res;
	MYSQL_ROW row;
	char q[1024];
	char* ret;
	int num_rows;

//	fprintf(stderr,"SQL1\n");
	sprintf(q,"SELECT bounce_msg FROM mailbox WHERE igw_login='%s' AND pop3_email='%s';",igw_login,mailbox);
	if(mysql_query(sock,q)){
		sprintf(q,"Query: \"%s\" failed ! %s\n",q,mysql_error(sock));
		return NULL;
	}
//	fprintf(stderr,"SQL2\n");
	if (!(res=mysql_store_result(sock))){
		fprintf(stderr,"Couldn't get result from %s\n",mysql_error(sock));
		return NULL;
	}
//	fprintf(stderr,"SQL3\n");
	num_rows = mysql_num_rows(res);
	if(num_rows != 1){
		mysql_free_result(res);
		return NULL;
	}
//	fprintf(stderr,"SQL4\n");
	row = mysql_fetch_row(res);
	// No bounce message stored ?
	if(row == NULL){
//		fprintf(stderr,"Couldn't fetch row: %s\n",mysql_error(sock));
		mysql_free_result(res);
		return NULL;
	}
//	fprintf(stderr,"SQL5\n");
	if(row[0] != NULL)
		ret=strdup(row[0]);
	else
		ret=NULL;
	mysql_free_result(res);
//	fprintf(stderr,"SQL6\n");
//	printf("founded:%s\n",ret);
	return (ret);
}
