/*
*	Stub for charge authorization program.
*/
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>

FILE	*log;
char	*pipe_name = NULL;
void	bad_exit(str)
	char*	str;
{
  int	out;
  fprintf (log, "%s\n", str);
  fclose (log);
  if (pipe_name == NULL || (out = open (pipe_name, O_WRONLY)) < 0)
    {
       fprintf (log, "%s  <-> %s\n", str, "Bad exit Could not open output pipe.");
    }
  else
   {
     write (out, "-1:\n", strlen ("-1:\n"));
     close (out);
   }
  exit (-1);
}
void	on_kill(sig)
	int	sig;
{
	exit (-1);
}
static	char	Usage[] = "auth-pr output-pipe-file-name";
int	main(argc, argv)
	int	argc;
	char	**argv;
{
  char	buf[256];
  char	buf1[256];
  log = fopen ("/tmp/auth-pr.log", "a");

  if (argc != 2)
    bad_exit (Usage);

  pipe_name = argv[1];

  if (fgets(buf, 256, stdin) != NULL)
    {
      pid_t	child;

      if ((child = fork ()) > 0)
	{
	  int	i, status, waitrv;
	  for (i = 0; i < 10; i++)
	    {
	      fprintf (log, "waiting started\n");
	      if ((waitrv = waitpid (child, &status, WNOHANG)) == 0)
		{
		  fprintf (log, "child not ready\n");
		  sleep (1);
		  continue;
		}
	      else
		{
		  fprintf (log, "error with waitpid %d\n", waitrv);
		  break;
		}
	    }
	  if (i == 10)
	    {
	      fprintf (log, "timeout\n");
	      kill (child, SIGKILL);
	    }
	  if (waitrv == child)
	    {
	      fprintf (log, "child is over\n");
	      if (WIFEXITED(status))
		{
		  fprintf (log, "child is Ok\n");
		  return 0;
		}
	      else
		{
		  fprintf (log, "child is not Ok\n");
		  return -1;
		}
	    }
	}
      else if (child == 0)
	{
          FILE	*p;
	  signal (SIGKILL, on_kill);
          p = fopen ("/usr/local/libexec/gnats/cards", "r+");
          if (p != NULL)
	    {
	      int	tn;
	      fgets (buf1, 256, p);
	      sscanf (buf1, "%d", &tn);
    
	      while (fgets (buf1, 256, p))
	        if (!strcmp(buf, buf1))
	          {
		     int	out;
		     fprintf (log, "%s\n", pipe_name);
		     if ((out = open (pipe_name, O_WRONLY)) < 0)
		       {
		         fclose (p);
		         fprintf (log, "errno is %d\n", errno);
		         bad_exit ("Could not open output pipe.");
		       }
		     else
		       {
		         char	buf[256];
		         sprintf (buf, "24:transaction %d\n", tn);
		         write (out, buf, strlen (buf));
		         close (out);
		         rewind (p);
		         fprintf (p, "%16d\n", ++tn);
		         fclose (p);
		         fclose (log);
		         return 0;
		       }
    
	          }
              fclose (p);
	      bad_exit ("Number not found.");
            }
          else
	    bad_exit ("cards file not found.");
	}
      else
	bad_exit ("could not create a child.");
    }
  else
    bad_exit ("Cannot read from stdin.\n");
}
