#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <string.h>

int main(int argc, char ** argv)
{
	int  pid;
	int  fd;

	if (((argc == 3) && (strcmp(argv[1], "-a") == 0))|| argc == 2)
	{
		char * filename = argv[1];
		int flags = O_CREAT|O_WRONLY|O_TRUNC;

		if (argc == 3)
		{
			flags = O_CREAT|O_APPEND|O_WRONLY;
			filename = argv[2];
		}

		printf("About to run who into a file named: %s.\n", filename);

		if((pid = fork()) == -1)
		{
			perror("fork"); exit(1);
		}

		if (pid == 0)
		{
			close(1);
			fd = open(filename, flags, 0644);
			execlp("who", "who", NULL);
			perror("execlp");
			exit(1);
		}

		if (pid != 0)
		{
			wait(NULL);
			printf("Done running who. Results are in file named: %s.\n", filename);
		}
	} else if (argc == 1) {
		system("who");
	} else {
		printf("Usage:\n\twhotofile\t - prints who to stdout\nOR\n\twhotofile FILE\t - saves result of who into a file and removes old content if exists\nOR\n\twhotofile -a FILE\t - saves result of who to file and appends if file exists\n");
		exit(1);
	}

	exit(0);
}
