#include <signal.h>
#include <sys/time.h>
#include <fcntl.h>

#define print(d,message) write(d,message,strlen(message))
#define print_nl(d,message) (print(d,message),write(d,"\n",1))

char response[100];
int def_reply=1;
int tty;

void leave(rc)
int rc;
/* This routine gets called instead of exit() so that ask can do any
   cleanup explicitely. */
{
  close(tty);
  exit(rc);
}

void print_response()
/* This routine prints whatever the response that will be returned is and
   exits with no error status. */
{
  if (!isatty(1) || def_reply)
      print_nl(1,response);
  if (!isatty(1) && def_reply)
      print_nl(tty,response);
  leave(0);
}

int alrm()
/* This is the alarm handler for timeout.  The response is printed. */
{
  print_response();
  return(0);
}

void usage()
{
  print(2,"Usage: ask timeout default message\n");
  print(2,"       timeout is number of seconds until timeout\n");
  print(2,"       default is default response\n");
  print(2,"       message is question to be asked\n");
  leave(1);
}

main(argc,argv)
int argc;
char *argv[];
{
    int timeout;
    char *def_response;
    char *message;
    
    struct itimerval timer;
    
    if (argc != 4)
	{
	    usage();
	}
    
    /* Parse command line options. */
    timeout = atoi(argv[1]);
    def_response = argv[2];
    message = argv[3];

    /* Make sure that response contains the default response so that the
       right thing will happen if the program times out. */
    strcpy(response,def_response);
    
    /* Cause ask to call alrm() if it receives SIGALRM. */
    signal(SIGALRM,alrm);
  
    /* Set up an itimer structure to send an alarm signal after timeout
       seconds. */
    timer.it_interval.tv_sec = timeout;
    timer.it_interval.tv_usec = 0;
    timer.it_value = timer.it_interval;
  
    /* Open the tty here before leave() ever gets called. */
    tty = open("/dev/tty",O_WRONLY,0);
    
    /* Start the timer. */
    if (setitimer (ITIMER_REAL, &timer, (struct itimerval *)0) < 0)
	{
	    perror("setitimer");
	    leave(1);
	}
    
    /* Print the message and wait for a response. */
    print(tty,message);
    read(0,response,sizeof(response));
    signal(SIGALRM, SIG_IGN);

    for (message=response; *message; message++)
	if (*message == '\n')
	    {
		*message = '\0';
		continue;
	    }
    def_reply=0;
    print_response();
    leave(0);
    
    /* Follow ansi standard and make hc happy. */
    exit(0);
}
