#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
#include <getopt.h>
#include <string.h>
#include <fcntl.h>
#include <signal.h>
#include <errno.h>
#include <string.h>
#include <limits.h>
#include <sys/types.h>
#include <pwd.h>
#include <sys/time.h>
#include <math.h>

#include "message.h"
#include "bounce.h"
#include "smtp.h"
#include "my_strings.h"
#include "sql_query.h"
#include "getmx.h"
#include "exit.h"

char* saveMessageAndGetRandom(tMsg* msg){
	struct timeval tv;
	struct timezone tz;
	long zerandom;
	static char buff[32];
	char* escaped_msg;

	gettimeofday(&tv,&tz);
	srand(tv.tv_usec);	// Initialise random generator with micro second value
	zerandom = rand();

	sprintf(buff,"%ld%ld",tv.tv_sec,zerandom);	// Our number is curent timestamp in second concatened with random value
	escaped_msg = addSlashes(msg->readMessage(),msg->m_size);
	saveMessageToSql(buff,msg->m_head->m_iWall_user,
		msg->m_head->m_fetchmail_email_addr,escaped_msg,msg->m_head->m_Subject_feild,msg->m_head->m_from_email);
	free(escaped_msg);
	return(buff);
}

void bounceMessage(tMsg* msg){
	char* subject;
	char* random_string;
	char* custom_bounce=NULL;
	char* msgcore;
	char* crlf;
	char* url_replaced;
	char* unescaped;
	char url[1024];
	unsigned long coreSize;
	int mx_number;
	char mx_buf[1024];
	char* normal_bounce="Hello ! This is a bounce message that show you \
URL to click to write to me. Do not hesitate, this is only check to know if \
your address is not spam. Just click on the following link, type the number, \
and the message you sent me will reach me.\n
\n
!!!URL!!!\n
\n
";
	fprintf(stderr,"[igw]Bouncing to:'%s'\n",msg->m_head->m_from_email);
	// try to resolv the MX of the message first
	mx_number = getmx(mx_buf,msg->m_head->m_from_domain,1023);
	if(mx_number == 0){
		fprintf(stderr,"[igw]DENY: FROM DOMAIN HAS NO RESOLVABLE_MX\n");
		exit(EXIT_FROM_DOMAIN_HAS_NO_RESOLVABLE_MX);
		return ;
	}
	fprintf(stderr,"TEST1\n");
	subject = (char*)malloc(1+strlen("Re: [iGW] ")+strlen(msg->m_head->m_Subject_feild));
	if(subject == NULL){
		exit(EXIT_CANNOT_MALLOC);
	}
	fprintf(stderr,"TEST2\n");
	strcpy(subject,"Re: [iGW] ");
	strcat(subject,msg->m_head->m_Subject_feild);
	fprintf(stderr,"TEST3\n");
	random_string = saveMessageAndGetRandom(msg);
	fprintf(stderr,"TEST4\n");
	if(random_string == NULL)	return;
	sprintf(url,"%s%s",IGW_URL,random_string);
	fprintf(stderr,"TEST5\n");
	custom_bounce = getCustomBounceMessage(msg->m_head->m_iWall_user,msg->m_head->m_fetchmail_email_addr);
	if(custom_bounce != NULL && strlen(custom_bounce) > 8){
		msgcore = custom_bounce;
	}else{
		msgcore = normal_bounce;
	}
	fprintf(stderr,"TEST6\n");
	coreSize = strlen(msgcore);
	fprintf(stderr,"TEST7\n");
	crlf = lf2crlf(msgcore,&coreSize);
	fprintf(stderr,"TEST8\n");
	url_replaced = str_replace(crlf,"!!!URL!!!",url);
	ESMTP_send_message("iGlobalWall Daemon","iglobalwalldaemon@iglobalwall.com",
		msg->m_head->m_from_email,subject,url_replaced);

}
