/**********************************************************************
 * luc_who.c -- get array of users and their levels of luciness
 *
 * $Author: brlewis $
 * $Source$
 * $Header$
 *
 * Copyright 1991 by the Massachusetts Institute of Technology.
 *
 * For copying and distribution information, please see the file
 * <mit-copyright.h>.
 **********************************************************************/
#include <mit-copyright.h>

#ifndef lint
static char rcsid_luc_who_c[] = "$Header$";
#endif /* lint */

#include <stdio.h>
#include <strings.h>
#include <errno.h>
#include <krb.h>
#include <lucy/memory.h>
#include <lucy/lucy.h>

/**********************************************************************
 * luc_who(lacl_entry **retval)
 *
 * - allocates and fills in array of users and their levels of luciness
 * - returns error code
 **********************************************************************/

long
luc_who(retval)
     lacl_entry **retval;
{
  long code;
  dsc_acl *alist, *qlist;
  int i, j;
  char principal[MAX_K_NAME_SZ];
  char lrealm[REALM_SZ];
  int lev, nentries=0;
  char *at;

  /* read access control list */
  dsc_get_acl(&(luv_amtg.nb), &code, &alist);
  if (!code) dsc_get_acl(&(luv_qmtg.nb), &code, &qlist);
  if (code)
    {
      strcpy(luv_context, "getting acl");
      return(code);
    }

  /* allocate space for return value */
  *retval = NewArray(lacl_entry, alist->acl_length+1);
  if (!*retval)
    {
      *luv_context = '\0';
      return((long) ENOMEM);
    }

  /* get local realm */
  krb_get_lrealm(lrealm, 1);

  for(i=0; i<alist->acl_length; i++)
    {
      if (index(alist->acl_entries[i].modes, 'r'))
	{
	  lev=0;
	  /* find same principal in queue acl */
	  for(j=0; j<qlist->acl_length; j++)
	    if (!strcmp(alist->acl_entries[i].principal,
			qlist->acl_entries[j].principal)) break;
	  if (j >= qlist->acl_length) continue;

	  /* read access to queue means level 1 */
	  if (index(qlist->acl_entries[j].modes, 'r')) lev = 1;

	  /* write access to queue means level 2 */
	  if (index(qlist->acl_entries[j].modes, 'w')) lev = 2;

	  /* write access to archive means level 3 */
	  if (index(alist->acl_entries[i].modes, 'w')) lev = 3;

	  /* chairman access to queue means level 4 */
	  if (index(qlist->acl_entries[j].modes, 'c')) lev = 4;

	  if (lev)
	    {
	      /* shorten principal to username if in same realm */
	      strcpy(principal, alist->acl_entries[i].principal);
	      at = index(principal, '@');
	      if (at)
		if (!strcmp(at+1, lrealm)) *at='\0';
	      (*retval)[nentries].principal = newstring(principal);
	      if (!(*retval)[nentries].principal)
		{
		  *luv_context = '\0';
		  return((long) ENOMEM);
		}
	      strcpy((*retval)[nentries].principal, principal);
	      (*retval)[nentries].level = lev;
	      nentries++;
	    }
	}
    }
  (*retval)[nentries].principal = NULL;
  /* dsc_destroy_acl(alist); */
  /* dsc_destroy_acl(qlist); */
  return(0L);
}
