/*========================================================================
 * Written by D. Jason Penney, 1991.  Rights to this program are as follows:
 * you may not receive any compensation for distribution of this program
 * except for an optional fee for the distribution medium.  This program
 * must be accompanied by this source code.  This notice may not be removed.
 * Modifications to this program must be clearly noted and marked as such.
 * Since this program is provided free of charge, there is ABSOLUTELY NO
 * WARRANTY.
 *
 * Name - getid.c
 *
 * Description - 
 *
 * Compile with:
 *   cc -o getid getid.c
 *   chmod 555 getid
 *
 *
 * $Id: getid.c,v 1.2 2004-01-24 01:21:57 otisa Exp $
 *
 *========================================================================
 */

#include "flag.ht"
#include "global.ht"
#include "l2unix.hf"

#if !defined(WIN32)
static
const char *uidtostr(uid_t uid)
{
struct passwd *pw;

pw = getpwuid(uid);
if (pw == NULL)
  return "(unknown)";
return pw->pw_name;
}

static const char *gidtostr(gid_t gid)
{
struct group *thisGroup;

thisGroup = getgrgid(gid);
if (thisGroup == NULL)
  return "(unknown)";
return thisGroup->gr_name;
}
#endif /* WIN32 */

#ifndef WIN32
static void usage(void)
{
  printf("Usage:  getid [ -[n](ru|rg|eu|eg) ]\n");
}
#endif /* !WIN32 */

int main(int argc, char **argv)
{
#if defined(WIN32)
  #define USERNAMEMAX 256
  DWORD usernamesize = USERNAMEMAX;
  char username[USERNAMEMAX];
  argc = argc; /* lint */
  argv = argv; /* lint */
  if( GetUserName(username, &usernamesize) )
    printf("username=%s\n", username);
  else
    printf("GetUserName failed\n");
  return 0;
#else  
/* Be lazy, calculate everything */
uid_t uid = getuid();
gid_t gid = getgid();
uid_t euid = geteuid();
gid_t egid = getegid();

if (argc == 1) {
  printf("ruid=%s ", uidtostr(uid));
  printf("rgid=%s ", gidtostr(gid));
  printf("euid=%s ", uidtostr(euid));
  printf("egid=%s ", gidtostr(egid));
  }
else {
  if (argv[1][0] != '-') {
    usage();
    return 1;
    }
  if (strcmp(argv[1], "-nru") == 0)
    printf("%d", (int)uid);
  else
  if (strcmp(argv[1], "-nrg") == 0)
    printf("%d", (int)gid);
  else
  if (strcmp(argv[1], "-neu") == 0)
    printf("%d", (int)euid);
  else
  if (strcmp(argv[1], "-neg") == 0)
    printf("%d", (int)egid);
  else
  if (strcmp(argv[1], "-ru") == 0)
    printf("%s", uidtostr(uid));
  else
  if (strcmp(argv[1], "-rg") == 0)
    printf("%s", gidtostr(gid));
  else
  if (strcmp(argv[1], "-eu") == 0)
    printf("%s", uidtostr(euid));
  else
  if (strcmp(argv[1], "-eg") == 0)
    printf("%s", gidtostr(egid));
  else {
    usage();
    return 1;
    }
  }
if (isatty(fileno(stdout)))
  printf("\n");
return 0;
#endif /* !WIN32 */
}
