/*
 * zzh.c
 *
 * Shell for the "SSH Sleeping Beauty" user.
 *
 * (c) 1999, Tim Hemel <tim@n2it.net>
 *
 * $Id: zzh.c,v 1.1 1999/02/19 14:57:46 tim Exp $
 */

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

/* Timeout in seconds */
const int ZZZ = 10*60;
#define MAX_CMD_LEN 255

char cmd[MAX_CMD_LEN+1];

/* simple commandline parsing */
void parse_opt(int argc, char *argv[])
{
  int i,done;

  done = 0;
  for (i=0; (i<argc-1) && !done ; i++)
  {
    if (!strcmp(argv[i],"-c"))
    {
      strncpy(cmd,argv[i+1],MAX_CMD_LEN);
      cmd[MAX_CMD_LEN] = '\0';
      done = 1;
    }
  }
}

int main ( int argc, char* argv[] )
{
  int i;
  char *fn;
  int fd; 
  fd_set fs;
  struct timeval to;
  struct stat sb;

  signal( SIGPIPE, SIG_IGN);

  /* set cmd to "" */
  cmd[0]='\0';

  parse_opt(argc, argv);

  /* if no command string, exit */
  if (!strcmp(cmd,"")) exit(0);

  /* check what the command is */
  if (!strcmp(cmd,"open"))
  {
    /* create a temporary filename, which will be used as a magic word */
    fn = tmpnam(0); 
    fprintf(stdout,"%s\n",fn); fflush(stdout);
    /* fprintf(stderr,"#%s\n",fn); */
    /* create a named pipe with this name */
    if (!mkfifo(fn, 0600))
    {
      if ((fd = open(fn,O_RDONLY)) >0 )
      {
        /* set up a file descriptor set for select() */
        FD_ZERO(&fs);
        FD_SET(fd,&fs);
        /* set the ZZZ second timeout */
        to.tv_sec = ZZZ;

        /* wait for input and do nothing with it */
        if (select(fd+1, &fs, 0, 0, &to)>0)
        {
          /* lseek(fd,0,SEEK_END); /* not necessary */
        }
      }
    
      /* remove the temporary file */
      unlink(fn);
    }
  }
  else /* cmd != "" && cmd != "open" */
  {
    /* see if a file named cmd exists and is a named pipe */
    if (!stat(cmd,&sb))
    {
      if(sb.st_mode & S_IFIFO)
      {
        /* write to it */
        fd = open(cmd,O_WRONLY);
        if (fd > 0) { write(fd, "wake up", 1); }
      }
    } else { perror("stat"); }
  }
 
  /* return 0; */
  exit(0);
}
