#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <errno.h>

#define K	1024

char *pf = "/var/tmp/listen";

void cleanup(int sig)
{
  if (access(pf, F_OK) == 0)
    unlink(pf);
  exit(0);
}

void clear(void)
{
  pid_t pid = fork();
  if (pid == 0) {
    execlp("clear", "clear", NULL);
    perror("exec clear");
    exit(0);
  }
  wait(NULL);
}

int main(void)
{
  int r;
  char buf[K];

  if (access(pf, F_OK) != 0) {
    mkfifo(pf, 0666);
    chmod(pf, 0622);
  } else {
    printf("Listen is already running, exiting.\n");
    exit(0);
  }

  signal(SIGINT, &cleanup);
  clear();

  printf("Login to %s and use 'say' to anonymously chat to this terminal:\n",
	 getenv("HOSTNAME"));

  while (1) {
    int fd = open(pf, O_RDONLY);
    if (fd < 0) {
      perror("open pipe file");
      break;
    }
    while ((r = read(fd, buf, K)) > 0) {
      write(STDOUT_FILENO, buf, r);
    }
  }
  
  return 0;
}
