/* -------------------------------------------------------------------- */
/* -------------------------------------------------------------------- */

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <strings.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>

#include "url.h"
#include "base64.h"
#include "getopt.h"
#include "sockets.h"

#include "tslurp.h"
#include "twrite.h"
#include "tread.h"


/* -------------------------------------------------------------------- */

#define FALSE 	0
#define TRUE 	(!FALSE)

/* -------------------------------------------------------------------- */
/* -------------------------------------------------------------------- */
char *get_document(char *url, int *data_len, char *method, char *data, char *authentication, int *timeout)
{
	char 	send_buf[4096],
		tmp_buf[1024],
		*proxy,
		*auth,
		*mdata;

	


	int 	sockfd,
		orig_timeout,
		send_buflen,
		bytes_written;

	URL	*tmp_url,
		*proxy_url;


	if (timeout != NULL)
	{	orig_timeout = *timeout;
	}



	tmp_url = create_url();

	if (parse_url(url, tmp_url) == -1)
	{
		fprintf(stderr, "Error: Parsing URL '%s'\n", url);

		free_url(tmp_url);
		return NULL;
	}


	if ((proxy = getenv("HTTP_PROXY")) != NULL)
	{
		proxy_url = create_url();

		if (parse_url(proxy, proxy_url) == -1)
		{
			fprintf(stderr, "Error: Parsing proxy URL '%s'\n", proxy);

			free_url(tmp_url);
			free_url(proxy_url);
			return NULL;
		}


		sockfd = client_tconnect(proxy_url->host, atoi(proxy_url->port), timeout);
		if (sockfd == -1)
		{
			if ((timeout != NULL) &&
			    (orig_timeout != *timeout) &&
			    (*timeout == 0))
			{
				fprintf(stderr, "Error: Timeout expired connecting to '%s:%s'\n", proxy_url->host, proxy_url->port);
			}
			else
			{	fprintf(stderr, "Error: connecting to '%s:%s'\n", proxy_url->host, proxy_url->port);
			}	

			free_url(tmp_url);
			free_url(proxy_url);
			return NULL;
		}

		free_url(proxy_url);
	}
	else
	{	sockfd = client_connect(tmp_url->host, atoi(tmp_url->port));
		if (sockfd == -1)
		{
			if ((timeout != NULL) &&
			    (orig_timeout != *timeout) &&
			    (*timeout == 0))
			{
				fprintf(stderr, "Error: Timeout expired connecting to '%s:%s'\n", tmp_url->host, tmp_url->port);
			}
			else
			{	fprintf(stderr, "Error: connecting to '%s:%s'\n", tmp_url->host, tmp_url->port);
			}

			free_url(tmp_url);
			return NULL;
		}
	}



	/* Send the request for the page.	*/
	/* Using HTTP protocol version 1.0	*/

	sprintf(tmp_buf, "%s http://%s:%s%s HTTP/1.0\r\n", method, tmp_url->host, tmp_url->port, tmp_url->document);
	strcat(send_buf, tmp_buf);

#if 0
	sprintf(tmp_buf, "User-Agent: %s\r\n", "unknown");
	strcat(send_buf, tmp_buf);
#endif


#if 0
	if (proxy != NULL)
	{
		/* Send proxy related data.		*/

		sprintf(tmp_buf, "HOST: %s:%s\r\n", tmp_url->host, tmp_url->port);
		strcat(send_buf, tmp_buf);
	}
#endif


	if (data != NULL)
	{
		/* Send data appropriate to method.	*/
		/* POST or GET				*/

		if (strcmp(method, "GET") == 0)
		{	fprintf(stderr, "Error: Data supplied whilst method is 'GET'\n");

			free_url(tmp_url);
			return NULL;
		}
		else
		if (strcmp(method, "POST") == 0)
		{
			sprintf(tmp_buf, "Content-length: %d\r\n", strlen(data));
			strcat(send_buf, tmp_buf);
		}
		else
		{	fprintf(stderr, "Error: Data supplied whilst using Unsupport Method '%s'\n", method);

			free_url(tmp_url);
			return NULL;
		}
	}

	if (authentication != NULL)
	{
		/* Send Authentication.			*/
		/* Base64 Encode 'username:password' 	*/


		auth = encodeBase64(authentication);
		if (auth != NULL)
		{
			sprintf(tmp_buf, "Authorization: Basic %s\r\n", auth);
			strcat(send_buf, tmp_buf);

			free(auth);
		}
		else
		{	fprintf(stderr, "Error: Building authentication data\n");

			free_url(tmp_url);
			return NULL;
		}
	}


	strcat(send_buf, "\r\n");

	if (data != NULL)
	{	strcat(send_buf, data);
	}





	send_buflen   = strlen(send_buf);
	bytes_written = twrite(sockfd, send_buf, send_buflen, timeout);

	if (bytes_written != send_buflen)
	{
		/* An error ocurred during write */

		if ((timeout != NULL) &&
		    (orig_timeout != *timeout) &&
		    (*timeout == 0))
		{
			fprintf(stderr, "Error: Timeout expired while Sending data to server\n");
		}
		else
		{	fprintf(stderr, "Error: Sending data to server\n");
		}
	}
	else
	{	mdata = tslurp(sockfd, data_len, timeout);
		if (mdata == NULL)
		{
			if ((timeout != NULL) && 
			    (orig_timeout != *timeout) &&
			    (*timeout == 0))
			{
				fprintf(stderr, "Error: Timeout expired while Receiving data from server\n");
			}
			else
			{	fprintf(stderr, "Error: Receiving data from server\n");
			}
		}
	}


	client_disconnect(sockfd);
	free_url(tmp_url);
	return mdata;
}


/* -------------------------------------------------------------------- */
/* -------------------------------------------------------------------- */
static char *escape_input(char *src)
{
	char 	*buf, 
		*dst,
		*table = "0123456789ABCDEF";

	int	high,
		low;



	buf = (char *)malloc(sizeof(char) * (strlen(src) +1));
	if (buf == NULL)
	{	
		lprintf(LOG_ERROR, "malloc() failed\n");
		exit(EMALLOC);
	}


	dst = buf;
	while(*src != '\0') 
	{
		if (isalnum(*src))
		{
			*dst++ = *src;
		}
		else
		if (*src == ' ')
		{
			*dst++ = '+';
		}
		else
		{	

			low  = *src % 16;
			high = ((int)(*src / 16 )) % 16;

			*dst++ = '%';
			*dst++ = table[high];
			*dst++ = table[low];
		}
		
		src++;
	}

	*dst = '\0';
	return buf;
}


/* -------------------------------------------------------------------- */
/* -------------------------------------------------------------------- */
void usage(void)
{
	fprintf(stderr,"Usage: message <number> <message>\n");
}


/* -------------------------------------------------------------------- */
/* -------------------------------------------------------------------- */


/*

POST http://www.mtnsms.com/sms.asp HTTP/1.0
favs=&msgTo=%2B46709654321&msgText=this+is+a+test&msgCL=143&msgSig=0&butSUB=++++send++++&lenSSig=6&lenLSig=21&lenSysSig=11


*/



int main(int argc, char *argv[])
{
	int	document_len,
		i;

	char	*src, 
		*dst, 
		*url, 
		data[1024],
		*document,
		*ptr,
		*msg,
		num[512],
		*ac,
		*atmo,
		*rtmo,
		*prefix,
		*selectedintlprefix;

	if (argc != 3)
	{
		usage();
		exit(1);
	}


	/* ---------------------------------------- */

url = "http://www.mtnsms.com/sms.asp";

	/* ---------------------------------------- */




	sprintf(num, "%%2B%s", argv[1]);

	msg = escape_input(argv[2]);
	if (msg == NULL)
	{
		exit(1);
	}


sprintf(data, "favs=&msgTo=%s&msgText=%s&msgCL=143&msgSig=0&butSUB=++++send++++&lenSSig=6&lenLSig=21&lenSysSig=11",
	num, msg);


	free(num);
	free(msg);


	if (getenv("MTNDEBUG") != NULL)
	{
		fprintf(stderr, "DEBUG: Sending '%s'\n", data);
	}



	/* ---------------------------------------- */

	document = get_document(url, &document_len, "POST", data, NULL, NULL);
	if (document != NULL)
	{
		if (getenv("MTNDEBUG") != NULL)
		{
			printf("%s", document);
		}

		if (strstr(document, "spodrod") != NULL)
		{
			printf("Your message has been successfully queued for transmission\n");
		}
		else
		if (strstr(document, "spodrod") != NULL)
		{
			fprintf(stderr, "Error: Trying to Deliver message - didn't like your submission\n");
			exit(1);
		}
		else
		{	fprintf(stderr, "Error: Trying to Deliver message - Unexpected response\n");
			exit(1);
		}

		free(document);
	}
	else
	{
		fprintf(stderr, "Error: Trying to Deliver message - Failed to connect\n");
		exit(1);
	}


	return 0;
}
