/* 
 * Tell the user that they wanted to use a different machine
 */

#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define Request_Buffer_Size 8192

void main()
{
  char MyBuffer[Request_Buffer_Size];
  int  InputLen;


  fgets(MyBuffer, Request_Buffer_Size, stdin);

  /* This variable isn't really the length. It's one less than that. */
  InputLen = strlen(MyBuffer) - 1;

  /* This next chunk of code should strip off the last character if it's
     \r or \n, and if it was, then it'll strip off the penultimate character
     if it's \r or \n. */

  if ((MyBuffer[InputLen] == '\r') || (MyBuffer[InputLen] == '\n')) {
    MyBuffer[InputLen--] = '\0';
    if ((MyBuffer[InputLen] == '\r') || (MyBuffer[InputLen] == '\n')) {
      MyBuffer[InputLen--] = '\0';
    }
  }
  
  printf("HTTP/1.0 200 Document follows\r\n");
  printf("Last-modified: Tuesday, 18-Jun-74 00:00:00 GMT\r\n");
  printf("Date: Sunday, 18-Jun-74 00:00:00 GMT\r\n");
  printf("Server: Nocturne 14\r\n");
  printf("MIME-version: 1.0\r\n");
  printf("Content-type: text/html\r\n\r\n");
  printf("<HEADER><title>You're-using-the-wrong-server Message</title></HEADER>\r\n");
  printf("<h1>You're-using-the-wrong-server Message</h1>\r\n");

  printf("This machine used to be www.mit.edu, but that is no longer the\r\n");
  printf("case. If you came here from a document written by someone, we\r\n");
  printf("suggest that you let them know that they should only use the\r\n");
  printf("name \"<a href=\"http://www.mit.edu:8001/\">www.mit.edu</a>\"\r\n");
  printf("instead of whatever they specified that brought you here.<p>\r\n");

  /* If they made a GET request, then give them something to play with. */

  if (strstr(MyBuffer, "GET") == MyBuffer) {
    printf("<a href=\"http://www.mit.edu:8001/");

    /* This test is presuming that if a GET request (including the cr or crlf)
       is <= 5 characters that it's either malformed or is a request for "/";
       in either case, I'm going to point them to "/". */

    if (InputLen > 4) { /* Remember, InputLen is one less than the length. */

      char *walkstring = strstr(MyBuffer, " ");
      char *firstchar = NULL;
      char *lastchar  = MyBuffer + InputLen;

      if (walkstring != NULL) { /* If there was a space in MyBuffer */

	/* this scans either to the last character or the first nonspace */
	while ((++walkstring <= lastchar) && isspace(*walkstring)) {}
	
	/* if there's a space after the first chunk of spaces, then this
	   will truncate the string at it. */
	if (strstr(walkstring, " ") != NULL) {
	  *strstr(walkstring, " ") = '\0';
	}

	if (*walkstring == '/') {
	  ++walkstring;
	}

	if (walkstring <= lastchar) {
	  printf("%s", walkstring);
	}
      }
    }

    printf("\">Here is the URL you wanted to use.</a>\r\n");
  }
}

