/*
 *
 * Simple Basic Exec module for Screws 
 *
 */

#include "modskel.h"


char *type="exec",  /* execution module */
     *name="BasicExec"; /* rutinary msg */

int lbhosts_num=0;

bool init() /* Init function */
{
	char *lb_hosts=getenv("LB_HOSTS");
	char *next;

	if (lb_hosts) 
	{
	lb_hosts=strdup(lb_hosts);
	printf("[m] LoadBalancing to hosts: '%s'.\n",lb_hosts);

	/* TODO get a random host from this list */
    while(next = strchr(lb_hosts,' '))
		{
		lbhosts_num++;
        next[0] = '\0';
		printf("HOST: '%s'\n",lb_hosts);
		next[0] = ' ';
        lb_hosts=next+1;
		} 
	if(lb_hosts[0]) 
		{
		lbhosts_num++;
		printf("LAST HOST: %s\n",lb_hosts);
		}
	printf("Found %d hosts\n",lbhosts_num);
	} else {
		printf("[E] LoadBalancing failed: Please specify LB_HOSTS env\n");
	}
	return true;
}

bool exec(char **opts) /* Exec function */
{
	char *location=NULL;
	char *l=getenv("LB_HOSTS");

	location=l;
	if (1) /* Redirect */
	{
	printf(
	"HTTP/1.1 301 Moved Permanently\r\n"
	"Date: %s\r\n"
	"Server: screws %s\r\n"
	"Location: %s\r\n"
	//"Transfer-Encoding: chunked\r\n" len=e7
	"Content-Type: text/html; charset=iso-8859-1\r\n"
	"\r\n"
	"<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">"
	"<HTML><HEAD>\r\n"
	"<TITLE>301 Moved Permanently</TITLE>\r\n"
	"</HEAD><BODY>\r\n"
	"<H1>Moved Permanently</H1>\r\n"
	"The document has moved <A HREF=\"%s\">here</A>.<P>"
	"</BODY></HTML>\r\n"
	"\r\n",
		getenv("DATE"),
		getenv("VERSION"),
		location,
		location );
	return true; /* Break exec here! */
	}
	return false; /* Do the native Exec */
}
