/* $Id: nfs.pc 3956 2010-01-05 20:56:56Z zacheiss $
 *
 * This generates the files necessary to load an nfs server.
 *
 * Copyright (C) 1988-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 <moira_site.h>

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

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "util.h"

EXEC SQL INCLUDE sqlca;

RCSID("$HeadURL: svn+ssh://svn.mit.edu/moira/trunk/moira/gen/nfs.pc $ $Id: nfs.pc 3956 2010-01-05 20:56:56Z zacheiss $");

#define min(x, y)	((x) < (y) ? (x) : (y))

char *whoami = "nfs.gen";
char *db = "moira/moira";
char nfs_dir[MAXPATHLEN];
struct hash *users, *groups;

int do_nfs(void);
int do_lists(struct save_queue *lists);
void do_everyone(void);
int do_machs(struct save_queue *machs);

int main(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(nfs_dir, "%s/nfs", DCM_DIR);

  EXEC SQL CONNECT :db;

  changed = do_nfs();

  EXEC SQL COMMIT;

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

  if (argc == 2)
    {
      sprintf(cmd, "cd %s; cp %s/nfs/* .; tar cf %s .",
	      nfs_dir, MOIRA_DIR, argv[1]);
      if (system(cmd))
	exit(MR_TAR_FAIL);
    }

  exit(MR_SUCCESS);
}


/* Generate the files.  Returns zero if nothing changed, non-zero otherwise. */

int do_nfs(void)
{
  EXEC SQL BEGIN DECLARE SECTION;
  char machname[MACHINE_NAME_SIZE], listname[SERVERHOSTS_VALUE3_SIZE];
  EXEC SQL END DECLARE SECTION;
  struct save_queue *machs, *lists;
  int changed;

  machs = sq_create();
  lists = sq_create();

  /* 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 s_cursor CURSOR FOR
    SELECT m.name, s.value3
    FROM machine m, serverhosts s
    WHERE m.mach_id = s.mach_id AND s.service = 'NFS' AND s.enable != 0;
  EXEC SQL OPEN s_cursor;
  while (1)
    {
      EXEC SQL FETCH s_cursor INTO :machname, :listname;
      if (sqlca.sqlcode)
	break;
      sq_save_unique_string(machs, strdup(strtrim(machname)));
      sq_save_unique_string(lists, strdup(strtrim(listname)));
    }
  EXEC SQL CLOSE s_cursor;

  changed = do_lists(lists);
  EXEC SQL COMMIT;
  changed += do_machs(machs);
  return changed;
sqlerr:
  db_error(sqlca.sqlcode);
  exit(MR_DBMS_ERR);
}


/* Make all of the credentials lists that will be needed.  Returns 0 if
 * no files were actually changed
 */

int do_lists(struct save_queue *lists)
{
  char file[MAXPATHLEN], *u;
  FILE *fd;
  EXEC SQL BEGIN DECLARE SECTION;
  char *listname;
  int id;
  EXEC SQL END DECLARE SECTION;

  sprintf(file, "%s/list-", nfs_dir);

  /* build the list of everyone, and store it in a file whose name
   * corresponds to the empty list.
   */
  do_everyone();

  fprintf(stderr, "Building specific lists\n");
  /* now do each of the lists used by an NFS server */

  while (sq_get_data(lists, &listname))
    {
      if (strlen(listname) == 0)
	continue;
      sprintf(file, "%s/list-%s", nfs_dir, listname);
      fd = fopen(file, "w");
      if (!fd)
	{
	  fprintf(stderr, "cannot open %s for output\n", file);
	  exit(MR_OCONFIG);
	}

      EXEC SQL DECLARE m_cursor CURSOR FOR
	SELECT m.member_id
	FROM imembers m, list l
	WHERE m.list_id = l.list_id AND l.name = :listname
	AND m.member_type = 'USER'
	ORDER BY member_id;
      EXEC SQL OPEN m_cursor;
      while (1)
	{
	  EXEC SQL FETCH m_cursor INTO :id;
	  if (sqlca.sqlcode)
	    break;
	  if ((u = hash_lookup(users, id)))
	    fprintf(fd, "%s\n", u);
	}
      EXEC SQL CLOSE m_cursor;
      if (fclose(fd) == EOF)
	{
	  fprintf(stderr, "error closing %s\n", file);
	  exit(MR_CCONFIG);
	}
    }
/* don't free here either
    sq_destroy(lists);
 */
  return 1;
sqlerr:
  db_error(sqlca.sqlcode);
  exit(MR_DBMS_ERR);
}


/*  Build the list of everybody. */
struct grp {
  struct grp *next;
  char *lid;
};

struct user {
  char name[USERS_LOGIN_SIZE];
  int uid;
  struct grp *lists;
};


void do_everyone(void)
{
  const buflen = MAXPATHLEN;
  char buf[MAXPATHLEN], *l;
  struct user *u;
  struct grp *g;
  struct bucket *b, **p;
  EXEC SQL BEGIN DECLARE SECTION;
  char name[USERS_LOGIN_SIZE];
  int gid, id, lid, uid;
  EXEC SQL END DECLARE SECTION;
  FILE *fd;

  fprintf(stderr, "Building the list of everybody\n");
  sprintf(buf, "%s/list-", nfs_dir);
  fd = fopen(buf, "w");
  if (!fd)
    {
      fprintf(stderr, "cannot open %s for output\n", buf);
      exit(MR_OCONFIG);
    }

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

  /* retrieve simple groups */
  EXEC SQL DECLARE l_cursor CURSOR FOR
    SELECT gid, list_id
    FROM list
    WHERE nfsgroup != 0 AND grouplist != 0 AND active != 0
    ORDER BY list_id;
  EXEC SQL OPEN l_cursor;
  while (1)
    {
      EXEC SQL FETCH l_cursor INTO :gid, :lid;
      if (sqlca.sqlcode)
	break;
      sprintf(buf, ":%d", gid);
      hash_store(groups, lid, strdup(buf));
    }
  EXEC SQL CLOSE l_cursor;

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

  EXEC SQL DECLARE m_cursor2 CURSOR FOR
    SELECT list_id, member_id
    FROM imembers
    WHERE member_type = 'USER'
    ORDER BY list_id;
  EXEC SQL OPEN m_cursor2;
  while (1)
    {
      EXEC SQL FETCH m_cursor2 INTO :lid, :id;
      if (sqlca.sqlcode)
	break;
      if ((u = hash_lookup(users, id)) && (l = hash_lookup(groups, lid)))
	{
	  g = malloc(sizeof(struct grp));
	  g->next = u->lists;
	  u->lists = g;
	  g->lid = l;
	}
    }
  EXEC SQL CLOSE m_cursor2;

  for (p = &(users->data[users->size - 1]); p >= users->data; p--)
    {
      for (b = *p; b; b = b->next)
	{
	  u = (struct user *)b->data;
	  sprintf(buf, "%s:%d:101", u->name, u->uid);
	  for (g = u->lists; g; g = g->next)
	    {
	      if ((strlen(buf) + strlen(g->lid)) <= buflen)
		strcat(buf, g->lid);
	      else
		{
		  com_err(whoami, 0, "truncated server-side grp list for %s",
			  u->name);
		  break;
		}
	    }
	  b->data = strdup(buf);
	  fprintf(fd, "%s\n", buf);
	}
    }

  fclose(fd);
  return;

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


/* Now do each of the servers, linking the credentials list file and
 * compiling the quota and dirs files.
 */

int do_machs(struct save_queue *machs)
{
  EXEC SQL BEGIN DECLARE SECTION;
  char *machname, listname[SERVERHOSTS_VALUE3_SIZE];
  char dev[NFSPHYS_DEVICE_SIZE], dir[FILESYS_NAME_SIZE];
  char fstype[FILESYS_LOCKERTYPE_SIZE];
  int uid, quota, id, gid, flag1, flag2, flag3;
  EXEC SQL END DECLARE SECTION;
  char file[MAXPATHLEN], f1[MAXPATHLEN], f2[MAXPATHLEN], *cp;
  int prevuid, quotasum, olddev, oldmach;
  FILE *fd;
  struct hash *machines;

  fprintf(stderr, "Building machine files\n");

  machines = create_hash(100);
  while (sq_get_data(machs, &machname))
    {
      EXEC SQL SELECT s.value3, m.mach_id
	INTO :listname, :id
	FROM serverhosts s, machine m
	WHERE s.mach_id = m.mach_id AND m.name = :machname AND
	s.service = 'NFS';
      strtrim(machname);
      sprintf(f1, "%s/list-%s", nfs_dir, strtrim(listname));
      sprintf(f2, "%s/%s.cred", nfs_dir, machname);
      unlink(f2); /* ignore errors on this unlink */
      if (link(f1, f2))
	{
	  fprintf(stderr, "Cannot link %s to %s\n", f1, f2);
	  exit(MR_OCONFIG);
	}
      hash_store(machines, id, machname);
    }

  olddev = oldmach = -1;
  fd = stdin;

  EXEC SQL DECLARE q_cursor CURSOR FOR
    SELECT DISTINCT q.quota, q.entity_id, q.phys_id, n.device, n.mach_id
    FROM quota q, nfsphys n
    WHERE n.nfsphys_id = q.phys_id AND q.phys_id != 0 AND
    n.status < 16 AND q.type = 'USER'
    ORDER BY n.mach_id, q.phys_id, q.entity_id;
  EXEC SQL OPEN q_cursor;
  while (1)
    {
      EXEC SQL FETCH q_cursor INTO :quota, :uid, :flag1, :dev, :flag2;
      if (sqlca.sqlcode)
	break;
      if (flag1 != olddev || flag2 != oldmach)
	{
	  if (quotasum)
	    fprintf(fd, "%d %d\n", prevuid, quotasum);
	  if (flag2 == 0 || !hash_lookup(machines, flag2))
	    continue;
	  if (fd != stdin)
	    fclose(fd);
	  olddev = flag1;
	  oldmach = flag2;
	  while ((cp = strchr(dev, '/')))
	    *cp = '@';
	  sprintf(file, "%s/%s.%s.quotas", nfs_dir,
		  (char *)hash_lookup(machines, flag2), strtrim(dev));
	  fd = fopen(file, "w");
	  if (!fd)
	    {
	      fprintf(stderr, "cannot open %s for output\n", file);
	      exit(MR_OCONFIG);
	    }
	  prevuid = -1;
	  quotasum = 0;
	}
      if (uid != prevuid)
	{
	  if ((cp = hash_lookup(users, prevuid)) &&
	      (cp = strchr(cp, ':')))
	    prevuid = atoi(cp + 1);
	  if (quotasum)
	    fprintf(fd, "%d %d\n", prevuid, quotasum);
	  prevuid = uid;
	  quotasum = quota;
	}
      else
	quotasum += quota;
    }
  EXEC SQL CLOSE q_cursor;
  if ((cp = hash_lookup(users, prevuid)) &&
      (cp = strchr(cp, ':')))
    prevuid = atoi(cp + 1);
  if (quotasum)
    fprintf(fd, "%d %d\n", prevuid, quotasum);
  if (fd != stdin && fclose(fd) == EOF)
    {
      fprintf(stderr, "error closing %s", file);
      exit(MR_CCONFIG);
    }

  olddev = oldmach = -1;
  fd = stdin;
  EXEC SQL DECLARE q_cursor2 CURSOR FOR
    SELECT DISTINCT q.quota, q.entity_id, q.phys_id, n.device, n.mach_id,
    n.status
    FROM quota q, nfsphys n
    WHERE n.nfsphys_id = q.phys_id AND q.phys_id != 0 AND
    n.status > 15 AND q.type = 'GROUP'
    ORDER BY mach_id, phys_id, entity_id;
  EXEC SQL OPEN q_cursor2;
  while (1)
    {
      EXEC SQL FETCH q_cursor2 INTO :quota, :gid, :flag1, :dev,
	:flag2, :flag3;
      if (sqlca.sqlcode)
	break;
      if (flag1 != olddev || flag2 != oldmach)
	{
	  if (quotasum)
	    fprintf(fd, "%d %d\n", prevuid, quotasum);
	  if (flag2 == 0 || !hash_lookup(machines, flag2))
	    continue;
	  if (fd != stdin)
	    fclose(fd);
	  olddev = flag1;
	  oldmach = flag2;
	  while ((cp = strchr(dev, '/')))
	    *cp = '@';
	  sprintf(file, "%s/%s.%s.quotas", nfs_dir,
		  (char *)hash_lookup(machines, flag2), strtrim(dev));
	  fd = fopen(file, "w");
	  if (!fd)
	    {
	      fprintf(stderr, "cannot open %s for output\n", file);
	      exit(MR_OCONFIG);
	    }
	  prevuid = -1;
	  quotasum = 0;
	}
      if (gid != prevuid)
	{
	  if ((cp = hash_lookup(groups, prevuid)))
	    prevuid = atoi(cp + 1);
	  if (quotasum)
	    fprintf(fd, "%d %d\n", prevuid, quotasum);
	  prevuid = gid;
	  quotasum = quota;
	}
      else
	quotasum += quota;
    }
  EXEC SQL CLOSE q_cursor2;
  if ((cp = hash_lookup(groups, prevuid)))
    prevuid = atoi(cp + 1);
  if (quotasum)
    fprintf(fd, "%d %d\n", prevuid, quotasum);
  if (fd != stdin && fclose(fd) == EOF)
    {
      fprintf(stderr, "error closing %s", file);
      exit(MR_CCONFIG);
    }

  olddev = oldmach = -1;
  fd = stdin;

  EXEC SQL DECLARE q_cursor3 CURSOR FOR
    SELECT DISTINCT f.name, f.lockertype, u.unix_uid, l.gid, f.phys_id,
    f.mach_id, n.device
    FROM users u, list l, nfsphys n, filesys f
    WHERE u.users_id = f.owner AND l.list_id = f.owners
    AND f.createflg != 0 AND f.phys_id != 0 AND f.type = 'NFS'
    AND f.phys_id = n.nfsphys_id
    ORDER BY mach_id, phys_id;
  EXEC SQL OPEN q_cursor3;
  while (1)
    {
      EXEC SQL FETCH q_cursor3 INTO :dir, :fstype, :uid, :gid, :flag1,
	:flag2, :dev;
      if (sqlca.sqlcode)
	break;
      if ((flag1 != olddev || flag2 != oldmach) &&
	  hash_lookup(machines, flag2))
	{
	  if (fd != stdin)
	    fclose(fd);
	  olddev = flag1;
	  oldmach = flag2;
	  while ((cp = strchr(dev, '/')))
	    *cp = '@';
	  sprintf(file, "%s/%s.%s.dirs", nfs_dir,
		  (char *)hash_lookup(machines, flag2), strtrim(dev));
	  fd = fopen(file, "w");
	  if (!fd)
	    {
	      fprintf(stderr, "cannot open %s for output\n", file);
	      exit(MR_OCONFIG);
	    }
	}
      fprintf(fd, "%s %d %d %s\n", strtrim(dir), uid, gid, strtrim(fstype));
    }
  EXEC SQL CLOSE q_cursor3;
  if (fclose(fd) == EOF)
    {
      fprintf(stderr, "error closing %s", file);
      exit(MR_CCONFIG);
    }
  return 1;
sqlerr:
  db_error(sqlca.sqlcode);
  exit(MR_DBMS_ERR);
}

