/*
   qstat.c - Queue status indicator for Renaissoft Qfax 1.0
   (c) 1994 Robert LeBlanc and Renaissoft
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "qfax.h"

/* Non-exported function prototypes */

int count_pages(char *prefix);
char *get_file_date(char *file);

int count_pages(char *prefix)
{
/*
   Returns the number of pages in a fax document.
*/

  int pages = 0;
  char cmd[LINELEN];
  char tmp[LONGLEN];
  FILE *ls;

  sprintf(cmd, "%s -1 %s.[0-9][0-9][0-9]", LS, prefix);
  ls = popen(cmd, "r");
  while (fscanf(ls, "%s", tmp) != EOF)
    pages++;
  pclose(ls);
  return(pages);
}

char *get_file_date(char *file)
{
/*
   Returns the date and time stamp of a file as a string.
*/

  char file_date[SHORTLEN];
  char cmd[LINELEN];
  FILE *ls;

  sprintf(cmd, "%s -l %s | awk '{print $6, $7, $8}'", LS, file);
  ls = popen(cmd, "r");
  strcpy(file_date, getsline(ls));
  pclose(ls);
  return(file_date);
}

void main(void)
{
  int faxes = 0;
  int pages = 0;
  int nothing = 1;
  int code, i;
  FILE *ifp;
  char timestr[LONGLEN];
  char cmdlist[MAXFAXES][LINELEN];
  char dialstring[PHONELEN];
  char recipient[LONGLEN];
  char subject[LINELEN];
  char user[ALIASLEN];
  char sender[ALIASLEN];
  char status[LINELEN];
  char prefix[LINELEN];
  char shortprefix[LINELEN];
  char tmp[LINELEN];
  char *ptr;

  faxes = make_cmdlist(cmdlist);
  if (!faxes) {
    printf("No entries.\n");
    exit(EXIT_SUCCESS);
  }
  strcpy(user, getenv("USER"));
  for (i=0; i < faxes; i++) {
    get_cmdinfo(cmdlist[i], dialstring, recipient, subject);
    strcpy(prefix, make_prefix(cmdlist[i]));
    strcpy(sender, get_sender(prefix));
    if ((strcasecmp(user, "root") == 0) || (strcasecmp(user, sender) == 0)) {
      nothing = 0;
      pages = count_pages(prefix);
      sprintf(tmp, "%s.try", prefix);
      if ((ifp = fopen(tmp, "r")) == NULL) {
        strcpy(status, "Waiting to be sent.");
      } else {
        while (!feof(ifp)) {
          fscanf(ifp, "%d\n", &code);
	  strcpy(timestr, getsline(ifp));
        }
        fclose(ifp);
        sprintf(status, "Last attempted %s with result %d.",
	        timestr, code);
      }
      ptr = strrchr(prefix, '/');
      strcpy(shortprefix, (++ptr));
      printf("Fax ID Prefix: %s\n", shortprefix);
      printf("To: %s (%s), Pages: %d\n", dialstring, recipient, pages);
      if (strcasecmp(user, "root") == 0)
	printf("Sender: %s\n", sender);
      printf("Subject: %s\n", subject);
      printf("Queued: %s\n", get_file_date(cmdlist[i]));
      printf("Status: %s\n", status);
      printf("\n");
    }
  }
  if (nothing) {
    printf("No entries.\n");
  };
  exit(EXIT_SUCCESS);
}
