/* $Id: user_info.c,v 1.9 1999/06/17 03:22:13 levitte Exp $ */

#include "gnu_extras.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <descrip.h>
#include <starlet.h>
#include <stsdef.h>
#include <uaidef.h>
#include <jpidef.h>
#include "user_info.h"

struct itemlist3 {
    unsigned short buflen;
    unsigned short itemcode;
    void *bufaddr;
    unsigned short *resultlen;
};

static struct itemlist3 uaiitems[] = {
{ 0, UAI$_UIC, 0, 0 },
{ 0, UAI$_DEFDEV, 0, 0 },
{ 0, UAI$_DEFDIR, 0, 0 },
{ 0, 0, 0, 0 }
};

static struct itemlist3 useritems[] = {
{ 0, JPI$_USERNAME, 0, 0 },
{ 0, 0, 0, 0 }
};

int get_user_info(struct user_info *uai, unsigned long uic)
{
    unsigned short devlen, dirlen, unlen, uiclen;
    static char username[13];	/* Made static to please DEC C */
    $DESCRIPTOR(username_dsc, username);
    char *cp;
    int status;

    useritems[0].buflen = sizeof(username);
    useritems[0].bufaddr = username;
    useritems[0].resultlen = &unlen;

    status = sys$getjpiw(0, 0, 0, useritems, 0, 0, 0);
    if (!$VMS_STATUS_SUCCESS(status))
	return status;

    /* Trim spaces and NUL-terminate */
    for(cp = username + unlen; cp[-1] == ' '; cp--) ;
    *cp = '\0';
    unlen = cp - username;
    username_dsc.dsc$w_length = unlen;


    uaiitems[0].buflen = sizeof(uai->uic);
    uaiitems[0].bufaddr = &uai->uic;
    uaiitems[0].resultlen = &uiclen;

    uaiitems[1].buflen = sizeof(uai->device);
    uaiitems[1].bufaddr = &uai->device;
    uaiitems[1].resultlen = &devlen;

    uaiitems[2].buflen = sizeof(uai->directory);
    uaiitems[2].bufaddr = &uai->directory;
    uaiitems[2].resultlen = &dirlen;

    status = sys$getuai(0, 0, &username_dsc, uaiitems, 0, 0, 0);
    if (!$VMS_STATUS_SUCCESS(status))
	return status;

    /* Of course, the foolen variables are untrustable.  Look at the first
       byte in the strings instead... */
    devlen = *uai->device;
    dirlen = *uai->directory;

    /* Then remove the size byte from the string */
    memmove(uai->device, uai->device+1, devlen);
    uai->device[devlen] = '\0';
    memmove(uai->directory, uai->directory+1, dirlen);
    uai->directory[dirlen] = '\0';

    /* Make sure the directory has [] */
    for(cp = uai->directory; *cp != '\0'; cp++)
	if (*cp == '<') *cp = '[';
	else if (*cp == '>') *cp = ']';

    return status;
}
    
/* Emacs local variables

Local variables:
eval: (set-c-style "BSD")
end:

*/
