/*
 * web-mirror
 *
 * CGI program for requesting copying of pages from web.mit.edu
 * to www.mit.edu
 *
 * mhpower@mit.edu, 19 March 1998
 */

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>

main()
{
  int d, s, save_errno;
  struct stat st;
  char *c, error_msg[256];

  d = open("/var/www/web.mit.edu/copy_requested",
	   O_CREAT|O_EXCL|O_WRONLY, 0644);
  if (d == -1)
    {
      save_errno = errno;
      if (save_errno == EEXIST)
	{
	  strcpy(error_msg, "a copy request is already pending");
	  s = stat("/var/www/web.mit.edu/copy_requested", &st);
	  if (!s)
	    {
	      c = ctime(&(st.st_mtime));
	      c[24] = '\0';
	      strcat(error_msg, " since ");
	      strcat(error_msg, c);
	    }
	}
      else
	{
	  s = strerror(save_errno);
	  if (!s)
	    {
	      sprintf(error_msg, "unknown error %d", errno);
	    }
	  else
	    {
	      strncpy(error_msg, s, 128);
	      error_msg[127] = '\0';
	    }
	}
      print_header("failure");
      printf("<p>The copy request failed: %s</p>\n", error_msg);
      print_footer();
    }
  else
    {
      print_header("successful completion");
      printf(
       "<p>The copy request has been successfully queued on www.mit.edu</p>\n");
      print_footer();
    }
}

int print_header(s)
     char *s;
{
  puts("Content-Type: text/html\n");
  puts("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2 Final//EN\">");
  puts("<html>\n<head>");
  printf("<title>web-mirror: %s</title>\n", s);
  puts("<link rev=made href=\"mailto:webmaster@mit.edu\">");
  puts("</head>");
  fputs("<body bgcolor=\"#FFFFFF\" text=\"#000000\" link=\"#0000EE\" ", stdout);
  puts("vlink=\"#551A8B\" alink=\"#FF0000\">");
}

int print_footer()
{
  puts("</body>\n</html>");
}
