/* $Header: /afs/sipb.mit.edu/project/sipb-athena/repository/src/moira/gen/hesiod.dc,v 1.14 1996/06/02 07:42:32 ghudson Exp $
 *
 * This generates the zone files necessary to load a hesiod server.
 * The following zones are generated: passwd, uid, pobox, group,
 * grplist, gid, filsys, cluster, pcap, sloc, service.
 *
 *  (c) Copyright 1988, 1990 by the Massachusetts Institute of Technology.
 *  For copying and distribution information, please see the file
 *  <mit-copyright.h>.
 */

#include <mit-copyright.h>
#include <stdio.h>
#include <moira.h>
#include <moira_site.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <ctype.h>
EXEC SQL INCLUDE sqlca;


#ifdef ATHENA
#define HTYPE "UNSPECA"
#else
#define HTYPE "TXT"
#endif

/* max number of bytes of a data record that can be returned in a hesiod 
 * query.  This is 512 - overhead (~66) [derived empirically]
 */
#define MAXHESSIZE 446

char hesiod_dir[64];

#define min(x,y)	((x) < (y) ? (x) : (y))
struct hash *machines = NULL;
struct hash *users = NULL;
char *whoami = "hesiod.gen";

struct grp {
    struct grp *next;
    char *lid;
};
struct user {
    char name[9];
    struct grp *lists;
};

void lowercase();
char *malloc(), *strsave();


main(argc, argv)
int argc;
char **argv;
{
    char cmd[64];
    struct stat sb;
    int changed = 0;

    if (argc > 2) {
	fprintf(stderr, "usage: %s [outfile]\n", argv[0]);
	exit(MR_ARGS);
    }

    initialize_sms_error_table ();
    sprintf(hesiod_dir, "%s/hesiod", DCM_DIR);

#ifsql INGRES
    EXEC SQL CONNECT moira;
    EXEC SQL SET LOCKMODE SESSION WHERE LEVEL=TABLE, READLOCK=SHARED;
#endsql
#ifsql INFORMIX
    EXEC SQL DATABASE moira;
#endsql

    changed = do_passwd();
    changed += do_filsys();
    changed += do_cluster();
    changed += do_printcap();
    changed += do_palladium();
    changed += do_sloc();
    changed += do_service();
    changed += do_groups();

#ifsql INGRES
    EXEC SQL DISCONNECT;
#endsql
#ifsql INFORMIX
    EXEC SQL CLOSE DATABASE;
#endsql

    if (!changed) {
	fprintf(stderr, "No files updated.\n");
	if (argc == 2 && stat(argv[1], &sb) == 0)
	  exit(MR_NO_CHANGE);
    }

    if (argc == 2) {
	fprintf(stderr, "Building tar file.\n");
	sprintf(cmd, "cd %s; tar cf %s .", hesiod_dir, argv[1]);
	if (system(cmd))
	  exit(MR_TAR_FAIL);
    }

    exit(MR_SUCCESS);
}


get_mach()
{
    EXEC SQL BEGIN DECLARE SECTION;
    int id;
    char name[41];
    EXEC SQL END DECLARE SECTION;

    if (machines)
      return;

    machines = create_hash(1000);
    EXEC SQL DECLARE m_cursor CURSOR FOR
      SELECT name, mach_id
      FROM machine
      WHERE status = 1
      ORDER BY mach_id;
    EXEC SQL OPEN m_cursor;
    while (1) {
        EXEC SQL FETCH m_cursor INTO :name, :id;
        if (sqlca.sqlcode != 0) break;
	hash_store(machines, id, strsave(strtrim(name)));
    }
    if (sqlca.sqlcode < 0) db_error(sqlca.sqlcode);
    EXEC SQL CLOSE m_cursor;
#ifsql INGRES
    EXEC SQL COMMIT;
#endsql
#ifsql INFORMIX
    EXEC SQL COMMIT WORK;
#endsql
}


do_passwd()
{
    FILE *pout, *uout, *bout;
    char poutf[64], uoutf[64], poutft[64], uoutft[64], boutf[64], boutft[64];
    struct stat psb, usb, bsb;
    time_t ftime;
    struct user *u;
    char *mach;
    EXEC SQL BEGIN DECLARE SECTION;
    char login[9], shell[33], fullname[33], oa[17], op[13], hp[17];
    char nn[17], ptype[9];
    int uid, flag1, flag2, id, pid, status;
    EXEC SQL END DECLARE SECTION;

    sprintf(poutf, "%s/passwd.db", hesiod_dir);
    sprintf(uoutf, "%s/uid.db", hesiod_dir);
    sprintf(boutf, "%s/pobox.db", hesiod_dir);

    if (stat(poutf, &psb) == 0 && stat(uoutf, &usb) == 0 &&
	stat(boutf, &bsb) == 0) {
	ftime = min(min(psb.st_mtime, usb.st_mtime), bsb.st_mtime);
        if (ModDiff (&flag1, "users", ftime) ||
            ModDiff (&flag2, "machine", ftime))
            exit (MR_DATE);
	if (flag1 < 0 && flag2 < 0) {
	    fprintf(stderr, "Files passwd.db, uid.db, and pobox.db do not need to be rebuilt.\n");
	    return(0);
      }
    }

    sprintf(poutft, "%s~", poutf);
    pout = fopen(poutft, "w");
    if (!pout) {
	perror("cannot open passwd.db~ for write");
	exit(MR_OCONFIG);
    }
    sprintf(uoutft, "%s~", uoutf);
    uout = fopen(uoutft, "w");
    if (!uout) {
	perror("cannot open uid.db~ for write");
	exit(MR_OCONFIG);
    }
    sprintf(boutft, "%s~", boutf);
    bout = fopen(boutft, "w");
    if (!bout) {
	perror("cannot open pobox.db for write");
	exit(MR_OCONFIG);
    }

    fprintf(stderr, "Building passwd.db, uid.db, and pobox.db\n");
    get_mach();

    users = create_hash(12001);
    EXEC SQL DECLARE u_cursor CURSOR FOR
      SELECT login, uid, shell, fullname, nickname, office_addr,
      	     office_phone, home_phone, users_id, pop_id, potype, status
      FROM users
      WHERE status = 1 or status = 5 or status = 6
      ORDER BY users_id;
    EXEC SQL OPEN u_cursor;
    while (1) {
        EXEC SQL FETCH u_cursor INTO :login, :uid, :shell, :fullname, :nn,
                       :oa, :op, :hp, :id, :pid, :ptype, :status;
            if (sqlca.sqlcode != 0) break;
	    strtrim(login);
	    dequote(fullname);
	    dequote(nn);
	    dequote(oa);
	    dequote(op);
	    dequote(hp);
	    dequote(shell);
	    u = (struct user *) malloc(sizeof(struct user));
	    strcpy(u->name, login);
	    u->lists = NULL;
	    hash_store(users, id, u);
	    if (status == 1) {
		fprintf(pout, "%s.passwd\tHS %s \"%s:*:%d:101:%s,%s,%s,%s,%s:/mit/%s:%s\"\n",
			login, HTYPE, login, uid, fullname, nn, oa, op, hp,
			login, shell);
		fprintf(uout, "%d.uid\tHS CNAME %s.passwd\n", uid, login);
	    }
	    if (pid != 0 && (mach = hash_lookup(machines, pid))) {
		fprintf(bout, "%s.pobox\tHS %s \"POP %s %s\"\n",
			login, HTYPE, mach, login);
	    }
    }
    if (sqlca.sqlcode < 0) db_error(sqlca.sqlcode);
    EXEC SQL CLOSE u_cursor;
#ifsql INGRES
    EXEC SQL COMMIT;
#endsql
#ifsql INFORMIX
    EXEC SQL COMMIT WORK;
#endsql

    if (fclose(pout) || fclose(uout) || fclose(bout)) {
	fprintf(stderr, "Unsuccessful file close of passwd.db, uid.db, or pobox.db\n");
	exit(MR_CCONFIG);
    }
    fix_file(poutf);
    fix_file(uoutf);
    fix_file(boutf);
    return(1);
}


do_groups()
{
    FILE *iout, *gout, *lout;
    char ioutf[64], goutf[64], loutf[64], buf[2048], *l;
    struct hash *groups;
    register struct bucket *b, **p;
    struct grp *g;
    struct user *u;
    struct stat isb, gsb, lsb;
    time_t ftime;
    EXEC SQL BEGIN DECLARE SECTION;
    char name[33];
    int gid, id, lid, flag1, flag2, flag3, len;
    EXEC SQL END DECLARE SECTION;

    /* open files */
    sprintf(ioutf, "%s/gid.db", hesiod_dir);
    sprintf(goutf, "%s/group.db", hesiod_dir);
    sprintf(loutf, "%s/grplist.db", hesiod_dir);

    if (stat(ioutf, &isb) == 0 && stat(goutf, &gsb) == 0 && stat(loutf, &lsb) == 0) {
	ftime = min(isb.st_mtime, min(gsb.st_mtime, lsb.st_mtime));
        if (ModDiff (&flag1, "users", ftime) ||
            ModDiff (&flag2, "list", ftime) ||
            ModDiff (&flag3, "imembers", ftime))
            exit (MR_DATE);
	if (flag1 < 0 && flag2 < 0 && flag3 < 0) {
	    fprintf(stderr, "Files gid.db, group.db and grplist.db do not need to be rebuilt.\n");
	    return(0);
      }
    }

    sprintf(buf, "%s~", ioutf);
    iout = fopen(buf, "w");
    if (!iout) {
	perror("cannot open gid.db for write");
	exit(MR_OCONFIG);
    }
    sprintf(buf, "%s~", goutf);
    gout = fopen(buf, "w");
    if (!gout) {
	perror("cannot open group.db for write");
	exit(MR_OCONFIG);
    }
    sprintf(buf, "%s~", loutf);
    lout = fopen(buf, "w");
    if (!lout) {
	perror("cannot open grplist.db for write");
	exit(MR_OCONFIG);
    }

    fprintf(stderr, "Building gid.db, group.db, and grplist.db\n");

    /* make space for group list */
    groups = create_hash(15001);

    /* The following WHENEVER is declarative, not executed,
     * and applies for the remainder of this file only.
     */
    EXEC SQL WHENEVER SQLERROR GOTO sqlerr;

    /* get lock records */
    EXEC SQL SELECT modtime INTO :name FROM list WHERE list_id = 0;
    EXEC SQL SELECT modtime INTO :name FROM users WHERE users_id = 0;

    EXEC SQL DECLARE l_cursor CURSOR FOR
      SELECT name, gid, list_id
      FROM list
      WHERE grouplist != 0 AND active != 0
      ORDER BY list_id;
    EXEC SQL OPEN l_cursor;
    while (1) {
	EXEC SQL FETCH l_cursor INTO :name, :gid, :lid;
	if (sqlca.sqlcode != 0) break;
	strtrim(name);
	sprintf(buf, "%s:%d", name, gid);
	hash_store(groups, lid, strsave(buf));
	fprintf(iout, "%d.gid\tHS CNAME %s.group\n", gid, name);
	fprintf(gout, "%s.group\tHS %s \"%s:*:%d:\"\n",
		name, HTYPE, name, gid);
    }
    EXEC SQL CLOSE l_cursor;

    fflush(iout);
    fflush(gout);

    /* now do grplists */
    if (users == NULL) {
	users = create_hash(12001);
	EXEC SQL DECLARE u_cursor2 CURSOR FOR
	  SELECT users_id, login
	  FROM users
	  WHERE status = 1
	  ORDER BY users_id;
	EXEC SQL OPEN u_cursor2;
        while (1) {
	    EXEC SQL FETCH u_cursor2 INTO :id, :name;
	    if (sqlca.sqlcode != 0) break;
	    u = (struct user *) malloc(sizeof(struct user));
	    strcpy(u->name, strtrim(name));
	    u->lists = NULL;
	    hash_store(users, id, u);
	}
	EXEC SQL CLOSE u_cursor2;
    }

    EXEC SQL DECLARE i_cursor CURSOR FOR
      SELECT list_id, member_id
      FROM imembers
      WHERE member_type = 'USER'
      ORDER BY list_id;
    EXEC SQL OPEN i_cursor;
    while (1) {
	EXEC SQL FETCH i_cursor INTO :lid, :id;
	if (sqlca.sqlcode != 0) break;
	if (((l = hash_lookup(groups, lid)) != NULL) &&
	    (u = (struct user *) hash_lookup(users, id))) {
	    g = (struct grp *) malloc(sizeof(struct grp));
	    g->next = u->lists;
	    u->lists = g;
	    g->lid = l;
	}
    }
    EXEC SQL CLOSE i_cursor;
#ifsql INGRES
    EXEC SQL COMMIT;
#endsql
#ifsql INFORMIX
    EXEC SQL COMMIT WORK;
#endsql

    for (p = &(users->data[users->size - 1]); p >= users->data; p--) {
	for (b = *p; b; b = b->next) {
	    if ((g = ((struct user *)b->data)->lists) == NULL)
	      continue;
	    fprintf(lout, "%s.grplist\tHS %s \"",
		    ((struct user *)b->data)->name, HTYPE);
	    len = 0;
	    for (; g; g = g->next) {
		if (len + strlen(g->lid) + 1 < MAXHESSIZE) {
		    fputs(g->lid, lout);
		    if (g->next)
		      putc(':', lout);
		    len += strlen(g->lid) + 1;
		} else {
		    com_err(whoami, 0, "truncated grp list for user %s",
			    ((struct user *)b->data)->name);
		    break;
		}
	    }
	    fputs("\"\n", lout);
	}
    }

    if (fclose(iout) || fclose(gout) || fclose(lout)) {
	fprintf(stderr, "Unsuccessful close of gid.db, group.db, or grplist.db\n");
	exit(MR_CCONFIG);
    }
    fix_file(ioutf);
    fix_file(goutf);
    fix_file(loutf);
    return(1);
 sqlerr:
    db_error(sqlca.sqlcode);
    return(0);
}


do_filsys()
{
    FILE *out;
    char outf[64], outft[64], *mach, *group;
    register char *p;
    struct stat sb;
    time_t ftime;
    struct save_queue *sq, *sq2, *sq_create();
    EXEC SQL BEGIN DECLARE SECTION;
    char name[33], type[9], loc[81], access[2], mount[33], trans[257];
    char comments[65];
    int flag1, flag2, flag3, flag4, id, fid;
    EXEC SQL END DECLARE SECTION;
    char *index();

    sprintf(outf, "%s/filsys.db", hesiod_dir);

    if (stat(outf, &sb) == 0) {
	ftime = sb.st_mtime;

	if (ModDiff(&flag1, "filesys", ftime)) exit (MR_DATE);
	if (ModDiff(&flag2, "machine", ftime)) exit (MR_DATE);
	if (ModDiff(&flag3, "alias", ftime)) exit (MR_DATE);
	if (ModDiff(&flag4, "fsgroup", ftime)) exit (MR_DATE);

	if (flag1 < 0 && flag2 < 0 && flag3 < 0 && flag4 < 0) {
	    fprintf(stderr, "File filsys.db does not need to be rebuilt.\n");
	    return(0);
      }
    }

    sprintf(outft, "%s~", outf);
    out = fopen(outft, "w");
    if (!out) {
	perror("cannot open filsys.db for write");
	exit(MR_OCONFIG);
    }

    fprintf(stderr, "Building filsys.db\n");
    get_mach();
    sq = sq_create();
    sq2 = sq_create();

    EXEC SQL DECLARE f_cursor CURSOR FOR
      SELECT label, type, name, mach_id, access, mount, comments, filsys_id
      FROM filesys
      ORDER BY filsys_id;
    EXEC SQL OPEN f_cursor;
    while (1) {
	EXEC SQL FETCH f_cursor INTO :name, :type, :loc, :id, :access, 
                                   :mount, :comments, :fid;
	if (sqlca.sqlcode != 0) break;
	strtrim(type);
	if (!strcmp(type, "NFS") || !strcmp(type, "RVD")) {
	    if (mach = hash_lookup(machines, id)) {
		fprintf(out, "%s.filsys\tHS %s \"%s %s %s %s %s\"\n",
			strtrim(name), HTYPE, type, strtrim(loc), mach,
			strtrim(access), strtrim(mount));
	    }
	} else if (!strcmp(type, "AFS")) {
	    fprintf(out, "%s.filsys\tHS %s \"AFS %s %s %s\"\n",
		    strtrim(name), HTYPE, strtrim(loc), strtrim(access),
		    strtrim(mount));
	} else if (!strcmp(type, "ERR")) {
	    fprintf(out, "%s.filsys\tHS %s \"ERR %s\"\n",
		    strtrim(name), HTYPE, strtrim(comments));
	} else if (!strcmp(type, "FSGROUP")) {
	    sprintf(trans, "%s:%d", strtrim(name), fid);
	    sq_save_data(sq, strsave(trans));
	} else if (!strcmp(type, "MUL")) {
	    sprintf(trans, "%s:%d", strtrim(name), fid);
	    sq_save_data(sq2, strsave(trans));
	}
    }
    EXEC SQL CLOSE f_cursor;

    while (sq_get_data(sq, &group)) {
	fid = atoi(index(group, ':')+1);
	*index(group, ':') = 0;

	EXEC SQL DECLARE f_cursor2 CURSOR FOR
	  SELECT DISTINCT f.type, f.name, f.mach_id, f.access, f.mount,
		f.comments, f.label, g.key
	  FROM filesys f, fsgroup g
	  WHERE f.filsys_id = g.filsys_id AND g.group_id = :fid
	  ORDER BY key, label;
	EXEC SQL OPEN f_cursor2;
        while (1) {
            EXEC SQL FETCH f_cursor2 INTO :type, :loc, :id, :access,:mount,
                                    :comments, :name, :trans;
            if (sqlca.sqlcode != 0) break;
	    strtrim(type);
	    if (!strcmp(type, "NFS") || !strcmp(type, "RVD")) {
		if (mach = hash_lookup(machines, id)) {
		    fprintf(out, "%s.filsys\tHS %s \"%s %s %s %s %s\"\n",
			    group, HTYPE, type, strtrim(loc), mach,
			    strtrim(access), strtrim(mount));
		}
	    } else if (!strcmp(type, "AFS")) {
		fprintf(out, "%s.filsys\tHS %s \"AFS %s %s %s\"\n",
			group, HTYPE, strtrim(loc), strtrim(access),
			strtrim(mount));
	    } else if (!strcmp(type, "ERR")) {
		fprintf(out, "%s.filsys\tHS %s \"ERR %s\"\n",
			group, HTYPE, strtrim(comments));
    	    }
  	}
        EXEC SQL CLOSE f_cursor2;
	free(group);
    }
    sq_destroy(sq);

    while (sq_get_data(sq2, &group)) {
        fid = atoi(index(group, ':') + 1);
        *index(group, ':') = 0;
        fprintf(out, "%s.filsys\tHS %s \"MUL", group, HTYPE);
	EXEC SQL DECLARE f_cursor3 CURSOR FOR
	    SELECT DISTINCT f.label, g.key
	    FROM filesys f, fsgroup g
	    WHERE f.filsys_id = g.filsys_id AND g.group_id = :fid
	    ORDER BY key, label;
	EXEC SQL OPEN f_cursor3;
	while (1) {
	    EXEC SQL FETCH f_cursor3 INTO :name, :trans;
	    if (sqlca.sqlcode != 0) break;
            fprintf(out, " %s", strtrim(name));
	}
	EXEC SQL CLOSE f_cursor3;
        fprintf(out, "\"\n");
        free(group);
    }
    sq_destroy(sq2);

    EXEC SQL DECLARE a_cursor CURSOR FOR
      SELECT name, trans
      FROM alias
      WHERE type = 'FILESYS';
    EXEC SQL OPEN a_cursor;
    while (1) {
        EXEC SQL FETCH a_cursor INTO :name, :trans;
        if (sqlca.sqlcode != 0) break;
    	fprintf(out, "%s.filsys\tHS CNAME %s.filsys\n",
		strtrim(name), strtrim(trans));
    }
    EXEC SQL CLOSE a_cursor;
#ifsql INGRES
    EXEC SQL COMMIT;
#endsql
#ifsql INFORMIX
    EXEC SQL COMMIT WORK;
#endsql

    if (fclose(out)) {
	fprintf(stderr, "Unsuccessful close of filsys.db\n");
	exit(MR_CCONFIG);
    }
    fix_file(outf);
    return(1);
 sqlerr:
    db_error(sqlca.sqlcode);
    return(0);
}


/*
 * Modified from sys/types.h:
 */
int setsize;	/* = howmany(setbits, NSETBITS) */

typedef long	set_mask;
#define NSETBITS	(sizeof(set_mask) * NBBY)	/* bits per mask */
#ifndef howmany
#define	howmany(x, y)	(((x)+((y)-1))/(y))
#endif

#define	SET_SET(n, p)	((p)[(n)/NSETBITS] |=  (1 << ((n) % NSETBITS)))
#define	SET_CLR(n, p)	((p)[(n)/NSETBITS] &= ~(1 << ((n) % NSETBITS)))
#define	SET_ISSET(n, p)	((p)[(n)/NSETBITS] &   (1 << ((n) % NSETBITS)))
#define SET_CREATE()	((set_mask *)malloc(setsize * sizeof(set_mask)))
#define SET_ZERO(p)	bzero((char *)(p), setsize * sizeof(set_mask))
#define SET_CMP(p1, p2) (bcmp((p1), (p2), setsize * sizeof(set_mask)))

int nbitsset(set)
set_mask *set;
{
    int i, ret;
    ret = 0;
    for (i = 0; i < setsize * NSETBITS; i++)
      if (SET_ISSET(i, set))
	ret++;
    return(ret);
}


do_cluster()
{
    FILE *out;
    char outf[64], outft[64], *mach, machbuf[41], *p;
    struct stat sb;
    time_t ftime;
    EXEC SQL BEGIN DECLARE SECTION;
    int flag1, flag2, flag3, flag4, maxmach, maxclu, mid, cid, id;
    char name[41], label2[17], data[33];
    EXEC SQL END DECLARE SECTION;
    set_mask **machs, *ms, *ps;
    int oneclu;

    sprintf(outf, "%s/cluster.db", hesiod_dir);

    if (stat(outf, &sb) == 0) {
	ftime = sb.st_mtime;
        if (ModDiff (&flag1, "cluster", ftime)
            || ModDiff (&flag2, "machine", ftime)
            || ModDiff (&flag3, "mcmap", ftime)
            || ModDiff (&flag4, "svc", ftime)) exit (MR_DATE);
	if (flag1 < 0 && flag2 < 0 && flag3 < 0 && flag4 < 0) {
	    fprintf(stderr, "File cluster.db does not need to be rebuilt.\n");
	    return(0);
      }
    }

    sprintf(outft, "%s~", outf);
    out = fopen(outft, "w");
    if (!out) {
	perror("cannot open cluster.db for write");
	exit(MR_OCONFIG);
    }

    fprintf(stderr, "Building cluster.db\n");
    get_mach();

    EXEC SQL SELECT MAX(clu_id) INTO :maxclu FROM cluster;
    maxclu++;
    setsize = howmany(maxclu, NSETBITS);

    EXEC SQL SELECT MAX(mach_id) INTO :maxmach FROM machine;
    maxmach++;
    machs = (set_mask **)malloc((maxmach + 1) * sizeof(set_mask **));
    bzero(machs, (maxmach + 1) * sizeof(int));

    EXEC SQL DECLARE p_cursor CURSOR FOR
      SELECT mach_id, clu_id
      FROM mcmap
      ORDER BY mach_id;
    EXEC SQL OPEN p_cursor;
    while (1) {
        EXEC SQL FETCH p_cursor INTO :mid, :cid;
        if (sqlca.sqlcode != 0) break;
        if (!(ms = machs[mid])) {
	    ms = machs[mid] = SET_CREATE();
	    SET_ZERO(ms);
	}
	SET_SET(cid, ms);
    }
    EXEC SQL CLOSE p_cursor;

    for (mid = 1; mid < maxmach; mid++) {
	if (!machs[mid])
	  continue;
	ms = machs[mid];
	if (nbitsset(ms) > 1) {
	    oneclu = 0;
	    for (cid = 1; cid < maxclu; cid++) {
		if (SET_ISSET(cid, ms)) {
		    EXEC SQL DECLARE d_cursor CURSOR FOR
		      SELECT serv_label, serv_cluster
		      FROM svc
		      WHERE clu_id = :cid;
		    EXEC SQL OPEN d_cursor;
		    while (1) {
			EXEC SQL FETCH d_cursor INTO :label2, :data;
			if (sqlca.sqlcode != 0) break;
			strtrim(label2);
			strtrim(data);
			fprintf(out,
				"mrinternal-%d.cluster\tHS %s \"%s %s\"\n",
				mid, HTYPE, label2, data);
		    }
		    EXEC SQL CLOSE d_cursor;
		}
	    }
	} else {
	    oneclu = 1;
	    for (cid = 1; cid < maxclu; cid++)
	      if (SET_ISSET(cid, ms)) break;

	    EXEC SQL SELECT name INTO :name FROM cluster WHERE clu_id = :cid;
	    strtrim(name);
	}

	if (mach = hash_lookup(machines, mid)) {
	    for (p = machbuf; *mach && *mach != '.'; mach++)
	      *p++ = *mach;
	    *p = 0;
	    if (oneclu)
	      fprintf(out, "%s.cluster\tHS CNAME %s.cluster\n",
		      machbuf, name);
	    else
	      fprintf(out, "%s.cluster\tHS CNAME mrinternal-%d.cluster\n",
		      machbuf, mid);
	}
	for (id = mid + 1; id < maxmach; id++) {
	    if ((ps = machs[id]) && !SET_CMP(ms, ps)) {
		free(ps);
		machs[id] = NULL;
		if (mach = hash_lookup(machines, id)) {
		    for (p = machbuf; *mach && *mach != '.'; mach++)
		      *p++ = *mach;
		    *p = 0;
		    if (oneclu)
		      fprintf(out, "%s.cluster\tHS CNAME %s.cluster\n",
			      machbuf, name);
		    else
		      fprintf(out,
			      "%s.cluster\tHS CNAME mrinternal-%d.cluster\n",
			      machbuf, mid);
		}
	    }
	}
	free(ms);
	machs[mid] = NULL;
    }

    EXEC SQL DECLARE d_cursor2 CURSOR FOR
      SELECT c.name, d.serv_label, d.serv_cluster
      FROM svc d, cluster c
      WHERE c.clu_id = d.clu_id; 
    EXEC SQL OPEN d_cursor2; 
        while (1) { 
            EXEC SQL FETCH d_cursor2 INTO :name, :label2, :data; 
            if (sqlca.sqlcode != 0) break;
	    strtrim(name);
	    strtrim(label2);
	    strtrim(data);
	    fprintf(out, "%s.cluster\tHS %s \"%s %s\"\n",
		    name, HTYPE, label2, data);
    }
    free(machs);
#ifsql INGRES
    EXEC SQL COMMIT;
#endsql
#ifsql INFORMIX
    EXEC SQL COMMIT WORK;
#endsql

    if (fclose(out)) {
	fprintf(stderr, "Unsuccessful close of cluster.db\n");
	exit(MR_CCONFIG);
    }
    fix_file(outf);
    return(1);
 sqlerr:
    db_error(sqlca.sqlcode);
    return(0);
}


do_printcap()
{
    FILE *out;
    char outf[64], outft[64];
    struct stat sb;
    time_t ftime;
    EXEC SQL BEGIN DECLARE SECTION;
    char name[17], rp[17], sd[33];
    int flag1, flag2, ka, pc, rm, rq;
    EXEC SQL END DECLARE SECTION;

    sprintf(outf, "%s/printcap.db", hesiod_dir);

    if (stat(outf, &sb) == 0) {
	ftime = sb.st_mtime;
	if (ModDiff (&flag1, "printcap", ftime)
	    || ModDiff (&flag2, "machine", ftime))
	  exit (MR_DATE);
	if (flag1 < 0 && flag2 < 0) {
	    fprintf(stderr, "File printcap.db does not need to be rebuilt.\n");
	    return(0);
      }
    }

    sprintf(outft, "%s~", outf);
    out = fopen(outft, "w");
    if (!out) {
	perror("cannot open printcap.db for write");
	exit(MR_OCONFIG);
    }

    fprintf(stderr, "Building printcap.db\n");
    get_mach();

    EXEC SQL DECLARE p_cursor2 CURSOR FOR
      SELECT name, rp, dir, mach_id, auth, price, quotaserver
      FROM printcap;
    EXEC SQL OPEN p_cursor2; 
    while (1) { 
        EXEC SQL FETCH p_cursor2 INTO :name, :rp, :sd, :rm, :ka, :pc, :rq; 
        if (sqlca.sqlcode != 0) break;
	strtrim(name);
	strtrim(rp);
	strtrim(sd);
	fprintf(out, "%s.pcap\tHS %s \"%s:rp=%s:rm=%s:sd=%s:ka#%d:pc#%d",
		name, HTYPE, name, rp, hash_lookup(machines, rm), sd, ka, pc);
	if (rq)
	  fprintf(out, ":rq=%s\"\n", hash_lookup(machines, rq));
	else
	  fputs("\"\n", out);
    }
    EXEC SQL CLOSE p_cursor2;
#ifsql INGRES
    EXEC SQL COMMIT;
#endsql
#ifsql INFORMIX
    EXEC SQL COMMIT WORK;
#endsql

    if (fclose(out)) {
	fprintf(stderr, "Unsuccessful close of pcap.db\n");
	exit(MR_CCONFIG);
    }
    fix_file(outf);
    return(1);
 sqlerr:
    db_error(sqlca.sqlcode);
    return(0);
  }


do_palladium()
{
    FILE *out;
    char outf[64], outft[64];
    struct stat sb;
    time_t ftime;
    EXEC SQL BEGIN DECLARE SECTION;
    char name[33], trans[129];
    int flag, flag1, ident, rm;
    EXEC SQL END DECLARE SECTION;

    sprintf(outf, "%s/palladium.db", hesiod_dir);

    if (stat(outf, &sb) == 0) {
	ftime = sb.st_mtime;
	if ((ModDiff (&flag, "palladium", ftime)) ||
            (ModDiff (&flag1, "alias", ftime))) exit (MR_DATE);
	if (flag < 0 && flag1 < 0) {
	    fprintf(stderr, "File palladium.db does not need to be rebuilt.\n");
	    return(0);
      }
    }

    sprintf(outft, "%s~", outf);
    out = fopen(outft, "w");
    if (!out) {
	perror("cannot open palladium.db for write");
	exit(MR_OCONFIG);
    }

    fprintf(stderr, "Building palladium.db\n");
    get_mach();

    EXEC SQL DECLARE p_cursor3 CURSOR FOR
      SELECT name, ident, mach_id
      FROM palladium;
    EXEC SQL OPEN p_cursor3; 
    while (1) { 
        EXEC SQL FETCH p_cursor3 INTO :name, :ident, :rm;
        if (sqlca.sqlcode != 0) break;
	strtrim(name);
	fprintf(out,
		"%s.palladium\tHS %s \"%s %d %s interface directory\"\n",
		name, HTYPE, hash_lookup(machines, rm), ident, name);
    }
    EXEC SQL CLOSE p_cursor3;

    EXEC SQL DECLARE a_cursor2 CURSOR FOR
      SELECT name, trans
      FROM alias
      WHERE type = 'PALLADIUM';
    EXEC SQL OPEN a_cursor2; 
    while (1) { 
        EXEC SQL FETCH a_cursor2 INTO :name, :trans;
        if (sqlca.sqlcode != 0) break;
    	strtrim(name);
	strtrim(trans);
	fprintf(out, "%s.palladium\tHS %s \"%s\"\n", name, HTYPE, trans);
    }
    EXEC SQL CLOSE a_cursor2;
#ifsql INGRES
    EXEC SQL COMMIT;
#endsql
#ifsql INFORMIX
    EXEC SQL COMMIT WORK;
#endsql

    if (fclose(out)) {
	fprintf(stderr, "Unsuccessful close of palladium.db\n");
	exit(MR_CCONFIG);
    }
    fix_file(outf);
    return(1);
 sqlerr:
    db_error(sqlca.sqlcode);
    return(0);
}


do_sloc()
{
    FILE *out;
    char outf[64], outft[64], *mach;
    struct stat sb;
    time_t ftime;
    EXEC SQL BEGIN DECLARE SECTION;
    char service[17];
    int flag1, flag2, id;
    EXEC SQL END DECLARE SECTION;

    sprintf(outf, "%s/sloc.db", hesiod_dir);

    if (stat(outf, &sb) == 0) {
	ftime = sb.st_mtime;
	if ((ModDiff (&flag1, "serverhosts", ftime)) ||
	    (ModDiff (&flag2, "machine", ftime))) exit (MR_DATE);
	if (flag1 < 0 && flag2 < 0) {
	    fprintf(stderr, "File sloc.db does not need to be rebuilt.\n");
	    return(0);
      }
    }

    sprintf(outft, "%s~", outf);
    out = fopen(outft, "w");
    if (!out) {
	perror("cannot open sloc.db for write");
	exit(MR_OCONFIG);
    }

    fprintf(stderr, "Building sloc.db\n");
    get_mach();

    EXEC SQL DECLARE s_cursor CURSOR FOR
      SELECT DISTINCT service, mach_id
      FROM serverhosts
      ORDER BY service;
    EXEC SQL OPEN s_cursor; 
    while (1) { 
	EXEC SQL FETCH s_cursor INTO :service, :id;
	if (sqlca.sqlcode != 0) break;
	strtrim(service);
	if (mach = hash_lookup(machines, id))
	  fprintf(out, "%s.sloc\tHS %s %s\n", service, HTYPE, mach);
    }
    EXEC SQL CLOSE s_cursor;
#ifsql INGRES
    EXEC SQL COMMIT;
#endsql
#ifsql INFORMIX
    EXEC SQL COMMIT WORK;
#endsql

    if (fclose(out)) {
	fprintf(stderr, "Unsuccessful close of sloc.db\n");
	exit(MR_CCONFIG);
    }

    fix_file(outf);
    return(1);
 sqlerr:
    db_error(sqlca.sqlcode);
    return(0);
}

do_service()
{
    FILE *out;
    char outf[64], outft[64];
    struct stat sb;
    time_t ftime;
    EXEC SQL BEGIN DECLARE SECTION;
    char service[33], protocol[9], altserv[129];
    int port, flag1;
    EXEC SQL END DECLARE SECTION;

    sprintf(outf, "%s/service.db", hesiod_dir);

    if (stat(outf, &sb) == 0) {
	ftime = sb.st_mtime;
	if (ModDiff (&flag1, "services", ftime)) exit (MR_DATE);
	if (flag1 < 0) {
	    fprintf(stderr, "File service.db does not need to be rebuilt.\n");
	    return(0);
      }
    }

    sprintf(outft, "%s~", outf);
    out = fopen(outft, "w");
    if (!out) {
	perror("cannot open service.db for write");
	exit(MR_OCONFIG);
    }

    fprintf(stderr, "Building service.db\n");

    EXEC SQL DECLARE s_cursor2 CURSOR FOR
      SELECT name, protocol, port
      FROM services;
    EXEC SQL OPEN s_cursor2;
    while (1) { 
        EXEC SQL FETCH s_cursor2 INTO :service, :protocol, :port;
        if (sqlca.sqlcode != 0) break;
	lowercase(protocol);      /* Convert protocol to lowercase */
	strtrim(service);
	strtrim(protocol);
	fprintf(out, "%s.service\tHS %s \"%s %s %d\"\n",
		service, HTYPE, service, protocol, port);
    }
    EXEC SQL CLOSE s_cursor2;

    EXEC SQL DECLARE a_cursor3 CURSOR FOR
      SELECT name, trans
      FROM alias
      WHERE type = 'SERVICE';
    EXEC SQL OPEN a_cursor3; 
    while (1) { 
        EXEC SQL FETCH a_cursor3 INTO :service, :altserv;
        if (sqlca.sqlcode != 0) break;
	strtrim(service);
	strtrim(altserv);
	fprintf(out, "%s.service\tHS CNAME %s.service\n", service, altserv);
    }
    EXEC SQL CLOSE a_cursor3;
#ifsql INGRES
    EXEC SQL COMMIT;
#endsql
#ifsql INFORMIX
    EXEC SQL COMMIT WORK;
#endsql

    if (fclose(out)) {
	fprintf(stderr, "Unsuccessful close of service.db\n");
	exit(MR_CCONFIG);
    }
    fix_file(outf);
    return(1);
 sqlerr:
    db_error(sqlca.sqlcode);
    return(0);
}
