#include <sys/types.h>
#include <stdio.h>
#include <strings.h>
#include <signal.h>
#include <sys/file.h>
#include <sys/time.h>
#include <pwd.h>
#include <errno.h>


struct passwd *getpwuid();
int sigcount = 0;
int errno;

void setcount()
{
  ++sigcount; }

void outoftime()
{
  (void) printf("Out of time\n");
  exit(30); 
}

bong(i)
  int i;
{
  (void) printf("BONG at test # %d\n", i);
  exit(i);
}

main(argc, argv)
  int argc;
  char **argv;
{
  char Uname[100], filename[16], buff[100], randy_char;
  int Iuid, Uuid, sfd, Unamelen, f;
  struct timeval tp;

  Uuid = getuid();
  Iuid = geteuid();
  (void) seteuid(Uuid);

  (void) alarm(30) ;
  (void) signal(SIGALRM, outoftime) ;

  (void) gettimeofday(&tp, (struct timezone *) NULL);
  (void) srand((int) tp.tv_usec);
  if (argc != 4 || argv[2][3] || strcmp("cruel", argv[3]) < 0)
    bong(1);
  (void) read(0, buff, 1) ;
  if (errno != EBADF)
    bong(2) ;

  randy_char = (char) ((int) 'a' + rand() % 25);
  (void) write(10, &randy_char, 1);
  (void) strcpy(filename, "such_fun");
  filename[strlen(filename)+1] = '\0' ;
  filename[strlen(filename)] = randy_char ;
  sleep(2);

  f = open(filename, O_RDONLY) ;
  if (read(f, buff, 1))
    bong(3) ;

  ++filename[strlen(filename)-1] ;
  if (open(filename, O_RDONLY) >= 0)
    bong(4) ;

  randy_char = (char) ((int) '0' + rand() % 10) ;
  (void) write(10, &randy_char, 1) ;
  while (read(f, buff, 1) == 0)
    sleep(1); 
  if (buff[0] != randy_char)
    bong(5) ;

  --filename[strlen(filename)-1] ;
  (void) open(filename, O_RDWR) ;
  if (errno != ENOENT) {
    perror("open");
    bong(6) ; }

  (void) close(f);

  if (read(7, buff, 10) != 7)
    bong(7) ;
  (void) write(10, buff, 10) ;
  if (read(7, buff, 10) != 8)
    bong(8) ;
  (void) signal(SIGPIPE, SIG_IGN);
  (void) write(10, buff, 10) ;
  if (errno != EPIPE)
    bong(9);

  (void) signal(SIGWINCH, setcount);
  sleep(100);
  if (sigcount != 1)
    bong(10);

  if (read(7, buff, 10)) != 1)
    bong(11);
  (void) kill(getppid(), SIGALRM) ;
  if (read(7, buff, 10) != 1)
    bong(12);
  if (read(7, buff, 1))
    bong(13);

  (void) seteuid(Iuid);
  if ((sfd=open("/unc/brock/home7/THE.list",O_WRONLY|O_APPEND,0644)) == -1) {
    (void) printf("Open failed.  Send mail to brock.\n");
    exit(1); }
  (void) strcpy(Uname, getpwuid(Uuid)->pw_name);
  Unamelen = strlen(Uname);
  Uname[Unamelen++] = '\n';
  if (write(sfd, Uname, Unamelen) == Unamelen) {
    (void) printf("To THE.list is added %s", Uname);
    exit(0); }
  else {
    (void) printf("Write failed.  Send mail to brock.\n");
    exit(1); } }
