RCS_ID_C "$Id: user.c,v 1.2 1994/01/21 13:20:10 ppessi Exp $";
/*
 * user.c
 *
 * Get group and user names for their ids
 *
 * Author: ppessi <Pekka.Pessi@hut.fi>
 *
 * Copyright (c) 1993 Pekka Pessi
 *
 * Created      : Wed May 26 09:21:59 1993 ppessi
 * Last modified: Fri Jan 21 00:32:44 1994 ppessi
 *
 */

#include <exec/lists.h>
#include <exec/nodes.h>
#include <dos/var.h>

#if __SASC
#include <proto/exec.h>
#include <proto/dos.h>
#include <proto/usergroup.h>
#else
#error Unsupported Compiler.
#endif

#include <pwd.h>
#include <grp.h>

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

static char *wtoa(uid_t u);

/*
 * user
 *      Return user login for given uid. 
 *      Return also group ID if specified.
 *      Names have space filled up to 8 chars.
 *      Use a cache of 1 user
 */
UBYTE *
user(UWORD mu_uid)
{
  static UBYTE retval[9];		/* buffer to trash */
  static struct passwd *user = NULL;
  uid_t uid = MU2UG(mu_uid);

  /* Same as last one? */
  if (user && user->pw_uid == uid) {
    return retval;
  }

  if (user = getpwuid(uid)) {
    int i;
    for (i = 0; i < 8 && (retval[i] = user->pw_name[i]); i++)
      ;
    for (; i < 8; retval[i++] = ' ')
      ;
    retval[8] = '\0';
  } else {
    strcpy(retval, wtoa(uid));
  }

  return retval;
}

UBYTE * 
group(UWORD mu_gid)
{
  static UBYTE retval[9];		
  static struct group *group = NULL;
  gid_t gid = MU2UG(mu_gid);

  /* Same as last one? */
  if (group && group->gr_gid == gid) {
    return retval;
  }

  if (group = getgrgid(gid)) {
    int i;
    for (i = 0; i < 8 && (retval[i] = group->gr_name[i]); i++)
      ;
    for (; i < 8; retval[i++] = ' ')
      ;
    retval[8] = '\0';
  } else {
    strcpy(retval, wtoa(gid));
  }

  return retval;
}

/* 
 * wtoa
 */
static char *wtoa(uid_t id)
{
  UWORD w = id;
  short i; 
  static char b[9];

  b[5] = '\0';
  b[4] = w % 10 + '0'; w /= 10;
  b[3] = w % 10 + '0'; w /= 10;
  b[2] = w % 10 + '0'; w /= 10;
  b[1] = w % 10 + '0'; w /= 10;
  b[0] = w + '0';

  for (i = 0; b[i] == '0'; i++)
    ;
  if (b[i] == '\0')
    i--;

  return b + i;
}

