#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

int
main()
{
	struct stat st;
	char *f=getenv("FILE");
	char *h=getenv("HTTP");
	char *d=getenv("DATE");
	char *v=getenv("VERSION");
	char *file=0;
	FILE *fd;
	int len;
	char *b;

	if (!f||!h||!d||!v)
	{
		printf("Any required env-var not defined.\n");
		return 1;
	}

	file=(char *)malloc(strlen(f)+3); file[0]=0;

	if (f[0]=='/')	strcat(file,".");
		else    strcat(file,"./");
	strcat(file,f);

	if (strstr(file,".."))
	{
		// Simple Updir Protection.
		goto FileNotFound;
	}
	
	if (stat(file,&st))
		goto FileNotFound;

	if (S_ISDIR(st.st_mode))
	{
		free(file);
		file=strdup("./index.html");
		if (stat(file,&st))
			goto FileNotFound;
	}

	if (!(fd=fopen(file,"r")))
		goto FileNotFound;

        fseek(fd,0,SEEK_END);
	len=ftell(fd);
	fseek(fd,0,SEEK_SET);
	b=(char *)malloc(len);
	fread(b,len,1,fd);
	fclose(fd);

	if (!strcmp("1.1",getenv("HTTP")))
	{
		printf(
			"HTTP/1.1 200 OK\r\n"
			"Date: %s\r\n"
			"Server: Screws/%s running C script.\r\n"
			"Content-Type: text/html; charset=iso-8859-1\r\n"
			"Content-Length: %d\r\n"
			"\r\n",d,v,len);
		fflush(stdout);
	}

	write(1,b,len);
	return 0;

	FileNotFound:
	if (!strcmp("1.1",getenv("HTTP")))
	{
		printf( "HTTP/1.1 404 Not Found\r\n"
			"Date: %s\r\n"
			"Server: Screws/%s running C script.\r\n"
			"Connection: close\r\n"
			"Content-Type: text/html; charset=iso-8859-1\r\n"
			"\r\n",d,v );
	}
	printf( "<html>\n <head>\n  <title>NotFound</title>\n </head>"
		"\n <body>\n <b>File %s not found.</b>\n </body>\n</html>\r\n",file);
	free (file);

	return 0;
}
