/* zprstatd.c */

/*--------------------------------------------------------------------------*/

#include <stdio.h>
#include <strings.h>
#include "common.h"
#include "zprstat.h"
#include "Prntr.h"
#include "Lpq.h"
#include "Notice.h"

/*--------------------------------------------------------------------------*/

#define SLEEP_SECONDS 60

/*--------------------------------------------------------------------------*/

char*	program_name;
Bool	debug = FALSE;
char*	empty_string = "";

static	char	buffer[4096];
static	char*	filenames[] =
{
    "/usr/local/all.printers",
    "/mit/consult/lib/zprstat/all.printers",
    NULL,
};
static	char*	zprstat_class = "ZPRSTAT";
static	char*	update_instance = "UPDATE";
static	char*	printer_class = "PRINTER";

/*--------------------------------------------------------------------------*/

void	main(argc, argv)
int	argc;
char*	argv[];
{
    int i;
    Prntr* printers;
    Prntr* p;
    char* queue;
    char* msg;
    int priority = 15;

    for (i = 1; i < argc; i++)
      {
	  if ((strcmp(argv[i], "-d") == 0) ||
	      (strcmp(argv[i], "-debug") == 0))
	    {
		debug = TRUE;
		continue;
	    }
	  if ((strcmp(argv[i], "-p") == 0) ||
	      (strcmp(argv[i], "-priority") == 0))
	    {
		++i;
		priority = atoi(argv[i]);
	    }
      }

    program_name = argv[0];

    setpriority(0 /*PRIO_PROCESS*/, 0, priority);

    (void)Notice_Initialize(FALSE);
    printers = Prntr_Initialize(filenames);

    for (p = printers; p != NULL; p = Prntr_Next(p))
      Prntr_Find_Machine(p);

    Lpq_Init_Handler();

    if (debug)
      fprintf(stderr, "Initialization completed.\n");

    forever
      {
	  strcpy(buffer, empty_string);
	  for (p = printers; p != NULL; p = Prntr_Next(p))
	    {
		Prntr_Update(p);
		if ((queue = Lpq_Get_Queue(p)) != NULL)
		  Lpq_Parse_Queue(p, queue);

		if ((msg = Prntr_Change_Message(p)) != NULL)
		  {
		      Notice_Send(printer_class,
				  Prntr_Name(p),
				  Pstat_Unparse(Prntr_Curr_Status(p)),
				  msg);
		      Delete(msg);
		  }

		msg = Prntr_Update_Message(p);
		strcat(buffer, msg);
		Delete(msg);
	    }

	  Notice_Send(zprstat_class,
		      update_instance,
		      empty_string,
		      buffer);

	  sleep(SLEEP_SECONDS);
      }
}

/*--------------------------------------------------------------------------*/
