#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <utmpx.h>
#include <unistd.h>

#ifndef TRUE
# define TRUE  1
# define FALSE 0
#endif

static const char Version[] =
"Who Am I - 2010 - http://valroot.com/";

static int no_ssh_client = FALSE;

int main(int argc, char **argv)
{
int             c;
char            *tty, *p, *env;
struct utmpx protox, *utp;

	while ( (c = getopt(argc, argv, "VS")) != EOF )
	{
		switch (c)
		{
		  case 'V':
			puts(Version);
			exit(EXIT_SUCCESS);

		  case 'S':
			no_ssh_client = TRUE;
			break;

		  default:
			exit(EXIT_FAILURE);
		}
	}

	if ( ! no_ssh_client
	  && (env = getenv("SSH_CLIENT")) != 0
	  && (p = strchr(env, ' ')) != 0 )
	{
		*p = '\0';
		*p = '\0';
		puts(env);

		exit(EXIT_SUCCESS);
	}

	if ( (tty = ttyname(fileno(stdin))) == 0 )
	{
		fprintf(stderr, "cannot get tty [%s]\n", strerror(errno) );

		exit(EXIT_FAILURE);
	}

	if ( strncmp(tty, "/dev/", 5) == 0 )
		tty += 5;

	memset(&protox, 0, sizeof protox);
	strcpy(protox.ut_line, tty);

	if ( (utp = getutxline(&protox) ) == 0 )
	{
		fprintf(stderr, "cannot locate UTMPX for {%s}\n", tty);
		exit(EXIT_FAILURE);
	}


	{
#define	SZ sizeof(utp->ut_host)

		char	linebuf[1 + SZ];

		memcpy(linebuf, utp->ut_host, SZ);

		linebuf[SZ] = '\0';

		puts(linebuf);
	}

	return EXIT_SUCCESS;
}
