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

/* If SUNOS is defined then this function can be compiled to work on SunOS 
 * machines.  If SUNOS is undefined, then the function can be compiled to
 * work on Linux machines.
 */


#ifdef SUNOS
#include <utmpx.h>
#define _PATH_UTMP "/var/adm/utmpx"
#define UT_LINESIZE 22

#else 
#include <utmp.h>

#endif


/* Returns the name of the user sitting at the machine or NULL if
 * no one is sitting at the machine.
 *
 * The utmp file contains records that give information about who is currently
 * logged in.  This function reads through those records and tries to determine
 * if anyone is sitting at the console.  It assumes that on Linux if ut_line is
 * ":0" that the user is sitting at the machine.  Similarly, on Solaris, if 
 * ut_host is ":0.0", we assume that a user is sitting at the machine.
 */
char *
getUser()
{
    int rc;
    FILE *ut;
    char *user;

#ifdef SUNOS
    struct utmpx utmp;
#else
    struct utmp utmp;
#endif

    if ((ut = fopen(_PATH_UTMP, "r")) == NULL) {
	perror("");
	fprintf(stderr, "%s", _PATH_UTMP);
    }

    while((rc = fread(&utmp, sizeof(utmp), 1, ut)) > 0) {
	if (utmp.ut_name[0] == '\0')
	    continue;
	if (utmp.ut_type != USER_PROCESS)
	    continue;

#ifdef SUNOS
	if(utmp.ut_host != NULL && strstr(utmp.ut_host, ":0")) {
	  /*printf("user %s %d\n", utmp.ut_user, strlen(utmp.ut_user));*/
	  user = (char *)malloc(strlen(utmp.ut_user) +1);
	  strncpy(user, utmp.ut_user, strlen(utmp.ut_user) + 1);
	  /*printf("line %s\n", utmp.ut_line);*/
	  fclose(ut);
	  return user;
	}
#else
	if(utmp.ut_line != NULL && strstr(utmp.ut_line, ":0")) {
	  /*printf("user %s %d\n", utmp.ut_user, strlen(utmp.ut_user));*/

	  user = (char *)malloc(strlen(utmp.ut_user) +1);
	  strncpy(user, utmp.ut_user, strlen(utmp.ut_user) + 1);

	  /*printf("line %s\n", utmp.ut_line);*/
	  fclose(ut);
	  return user;
	}
#endif
    }
    fclose(ut);
    return(NULL);
}

