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

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <errno.h>
#include <unistd.h>
#include <sys/time.h>

#include "http_twrite.h"
#include "logfile/logfile.h"


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

static int timeout_flag;

/* -------------------------------------------------------------------- */
/* -------------------------------------------------------------------- */
static void timeout_func(int sig)
{	timeout_flag = 1;
}

/* -------------------------------------------------------------------- */
/* -------------------------------------------------------------------- */
int http_twrite(int fd, char *buf, int len, int *timeout)
{
	int 	using_timeout,
		bytes_written,
		total_written;

	time_t	start_time,
		new_timeout;


	void (* orig_signal)(int);



	bytes_written = 0;
	total_written = 0;
	using_timeout = 0;
	timeout_flag  = 0;

	if ((timeout != NULL) && 
	    (*timeout != 0))
	{
		using_timeout = 1;		

		start_time = time(NULL);
		orig_signal = signal(SIGALRM, timeout_func);
		alarm(*timeout);
	}


	lprintf(LOG_VERYVERBOSE, "http_write: '%s'\n", buf);


	while (len > 0 )
	{
		if (timeout_flag)
		{	
			*timeout = 0;
			signal(SIGALRM, orig_signal);

			return bytes_written;
		}

		bytes_written = write(fd, &buf[total_written], len);
		if (bytes_written == -1)
		{	
			if (errno != EINTR)
			{	break;
			}
		}
		else
		{	total_written += bytes_written;
			len           -= bytes_written;
		}
	}

	if (using_timeout)
	{
		alarm(0);
		signal(SIGALRM, orig_signal);

		new_timeout = (*timeout - (time(NULL) - start_time));
		if (new_timeout < 0)
		{	new_timeout = 0;
		}

		*timeout = new_timeout;		
	}

	return total_written;
}





