#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/utsname.h>
#include <utmp.h>
#include <time.h>

void sysInfo(void)
{
	struct utsname myUname;

	errno = (int)NULL;
	if (uname(&myUname) != 0)
	{
		perror("Blad uname()");
		return;
	}
	printf("uname(): sysname[]:\t%s\n", myUname.sysname);
	printf("uname(): nodename[]:\t%s\n", myUname.nodename);
	printf("uname(): release[]:\t%s\n", myUname.release);
	printf("uname(): version[]:\t%s\n", myUname.version);
	printf("uname(): machine[]:\t%s\n", myUname.machine);
	#ifdef _GNU_SOURCE
		printf("uname(): domainname[]:\t%s\n", myUname.domainname);
	#endif
}

void procInfo(void)
{
	system("ps auxwww");
	return;
}

char * showtime(time_t t)
{
	size_t bufSize = 15;
	char * buf = malloc(bufSize * sizeof(char));
	struct tm * tm;
	tm = localtime(&t);
	strftime(buf, bufSize, "%b %m %H:%M", tm);
	return buf;
}

void show_info(struct utmp *utbufp)
{
	char * myTty = ttyname(0);
	if (utbufp->ut_type != USER_PROCESS) return;
	printf("%-8.8s", utbufp->ut_name);
	printf(" ");
	printf("%-8.8s", utbufp->ut_line);
	printf(" ");
	printf("%10s", showtime((time_t)utbufp->ut_time));
	printf(" ");
#ifdef	SHOWHOST
	printf("(%s)", utbufp->ut_host);
#endif
	printf("\n");
	return;
}

void usersInfo(void)
{
	struct utmp	current_record;	/* read info into here       */
	int		utmpfd;		/* read from this descriptor */
	int		reclen = sizeof(current_record);

	if ( (utmpfd = open(UTMP_FILE, O_RDONLY)) == -1 ){
		perror( UTMP_FILE );	/* UTMP_FILE is in utmp.h    */
		exit(1);
	}

	while ( read(utmpfd, &current_record, reclen) == reclen )
		show_info(&current_record);
	close(utmpfd);
	return;
}
