/* $Id: pobox.pc,v 1.8 2002-03-15 18:11:19 zacheiss Exp $
 *
 * This generates a list of everyone's poboxes for the mitdir.
 *
 * Copyright (C) 1992-1998 by the Massachusetts Institute of Technology.
 * For copying and distribution information, please see the file
 * <mit-copyright.h>.
 */

#include <mit-copyright.h>
#include <moira.h>

#include <sys/stat.h>
#include <sys/types.h>

#include <ctype.h>
#include <stdio.h>
#include <string.h>

#include "util.h"

EXEC SQL INCLUDE sqlca;

RCSID("$Header: /afs/athena.mit.edu/astaff/project/moiradev/repository/moira/gen/pobox.pc,v 1.8 2002-03-15 18:11:19 zacheiss Exp $");

char *whoami = "pobox.gen";
char *db = "moira/moira";

int main(int argc, char **argv)
{
  FILE *out = stdout;
  char *outf = NULL, outft[MAXPATHLEN];
  int i;
  EXEC SQL BEGIN DECLARE SECTION;
  char login[USERS_LOGIN_SIZE], id[USERS_CLEARID_SIZE];
  char string[STRINGS_STRING_SIZE];
  EXEC SQL END DECLARE SECTION;

  EXEC SQL CONNECT :db;

  if (argc == 2)
    {
      outf = argv[1];
      sprintf(outft, "%s~", outf);
      if (!(out = fopen(outft, "w")))
	{
	  fprintf(stderr, "unable to open %s for output\n", outf);
	  exit(MR_OCONFIG);
	}
    }
  else if (argc != 1)
    {
      fprintf(stderr, "usage: %s [outfile]\n", argv[0]);
      exit(MR_ARGS);
    }
  else
    outf = NULL;

  /* The following is declarative, not executed,
   * and so is dependent on where it is in the file,
   * not in the order of execution of statements.
   */
  EXEC SQL WHENEVER SQLERROR GOTO sqlerr;

  EXEC SQL DECLARE x CURSOR FOR SELECT
    clearid, login
    FROM users WHERE status != 3 AND potype != 'NONE';
  EXEC SQL OPEN x;
  while (1)
    {
      EXEC SQL FETCH x INTO :id, :login;
      if (sqlca.sqlcode)
	break;
      strtrim(login);
      strtrim(id);
      if (isdigit(id[0]))
	fprintf(out, "%s %s@MIT.EDU\n", id, login);
    }

  EXEC SQL CLOSE x;

  EXEC SQL COMMIT;

  if (fclose(out))
    {
      perror("close failed");
      exit(MR_CCONFIG);
    }
  if (outf)
    fix_file(outf);
  exit(MR_SUCCESS);

sqlerr:
  db_error(sqlca.sqlcode);
  exit(MR_DBMS_ERR);
}
