/***************************************/
/* loglist.c                           */
/* EECS 338 - Assignment 1             */
/* Justin Hartman                      */
/***************************************/

#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>

int main(int argc, char *argv[]) {
  int i;
  pid_t cpid, w;
  int status;
  time_t t;
  char *cwd;

  if (argc < 2) {
    printf("Usage: loglist dir [log notes]\n\nPlease supply the name of a directory to list.");
    return -1;
  }

  cwd = (char *)malloc(128);
  getcwd(cwd, 127);

  if (chdir(argv[1])) {
    perror("Unable to list directory");
	free(cwd);
    return -1;
  }

  t = time(NULL);
  printf("%s: Listing of %s begun at %s from %s by %s.\n\n", argv[0], argv[1], ctime(&t), cwd, cuserid((char *)NULL));

  free(cwd);

  if (argc > 2) {
    printf("***** Log notes *****\n");
    for (i=2; i<argc; i++) {
      printf("%s\n", argv[i]);
    }
    printf("*********************\n");      
  }

  if ((cpid = fork())) {
    /* We're in the parent process */
    while ((w = wait(&status)) && (w != -1));
    printf("\n\nChild process %d completed listing\n", (int)cpid);
    return 0;
  } else {
    /* cpid == 0, so we're in the child process */
    printf("\nListing process %d forked by %d\n\n", (int)getpid(), (int)getppid());
    fflush(stdout);
    execlp("ls", "ls", "-al", (char *)NULL);
    return 0;
  }
}