/* 
   Copyright Andrew Tridgell 1997

   */
   

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>

#include "pserver.h"

#define LOGFILE "cvsweb.log"


int main(int argc, char *argv[])
{
  pid_t pid;
  int status=0;
  FILE *f;

  /* the first thing we do is run rsync to ensure that the fake repository
     is uptodate */
  if ((pid = fork())) {
    waitpid(pid, &status, 0);
  } else {

    /* we close stdin etc to ensure that rsync does not fiddle with any
       user input */
    close(0);
    close(1);
    close(2);

    open("/dev/null", O_RDWR);
    open("/dev/null", O_RDWR);
    open("/dev/null", O_RDWR);

    if (setgid(GID))
      exit(1);
    
    if (setuid(UID))
      exit(1);

    if (chdir(CHROOT_PATH)) 
      exit(1);

    return sync_trees();
  }


  /* now chroot - we don't want to do anything more outside the chrooted 
     area */
  if (chdir(CHROOT_PATH))
    exit(1);

  if (chroot(CHROOT_PATH))
    exit(1);


  /* log this connection */
  f = fopen(LOGFILE, "a");
  if (!f) exit(1);
  fprintf(f,"%s connect from %s (%s)\n", 
	  timestring(), getenv("REMOTE_HOST"), getenv("REMOTE_ADDR"));
  fclose(f);

  /* lose root privilages */
  if (setgid(GID))
    exit(1);

  if (setuid(UID))
    exit(1);

  return execl("/bin/cvsweb.pl", "cvsweb.pl", NULL);
}
