/* Simple UNIX like who on ATARI ST. Kees Lemmens; Oktober 1992

   UTMP must exist and be maintained by getty.
   
   Any questions or suggestions about this program can be send to:
   lemmens@dv.twi.tudelft.nl
*/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <utmp.h>
#include <signal.h>
#include "ux_misc.h"

void fatal(char *txt)
{	fprintf(stderr,"WHO: %s\n",txt);
	exit(1);
}

void main(int argc,char *argv[]) 
{	extern int utmp_fd;
	int type=USER_PROCESS,cnt=0;
	char *nam;
	struct utmp *w;

	if(argc==3)
		if(!strcmp(argv[1],"am"))
		{	if((nam=getenv("LOGNAME")) != NULL)	puts(nam);
			else								puts("No idea !\n");
			exit(0);
		}
	while(--argc>0)			/* parse options */
	{	if(*argv[1]=='-')
		{	switch(*(++argv[1]))
			{	case 'l':	type=LOGIN_PROCESS; break;
				default:	fatal("Usage= who [-l] | [am i]");
			}
			++argv;
		}
	}	
	setutent();
	
	while((w=getutent()) != NULL)
	{	if(w->ut_type == type)
		{	if(Pkill(w->ut_pid,SIGNULL) == 0) /* process exists ? */
			{	printf("%-8s %-*s %s",w->ut_user,(int)
				sizeof(w->ut_line),w->ut_line,ctime(&w->ut_time));
				cnt++;
			}
			else
			{	w->ut_type=DEAD_PROCESS;
				setutent();	pututline(w);	/* correct UTMP entry */
			}
		}
	}
	if(cnt==0)
		puts("No processes found\n");
	endutent();
	exit(0);
}
