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

#define MAXLINE 256
#define MAX_PASSWORD 10

#define SUCCESS "Password verified\n"
#define INVALID "Invalid password\n"
#define NO_USER "No such user\n"

int main(void) {
  char user_id[MAXLINE];
  char password[MAXLINE];

  /* The user will type in a user name on one line followed by a password 
     on the next.
     DO NOT add any prompts.  The only output of this program will be one 
	 of the messages defined above.
     Please read the comments in validate carefully
   */

  if(fgets(user_id, MAXLINE, stdin) == NULL) {
      perror("fgets");
      exit(1);
  }
  if(fgets(password, MAXLINE, stdin) == NULL) {
      perror("fgets");
      exit(1);
  }
  
  // TODO
  // check length of user id and password
  if (strlen(user_id) > MAX_PASSWORD || strlen(password) > MAX_PASSWORD) {
      printf("The user id or password are too long");
      exit(1);
  }
  //create pipe
  int pipefd[2];
  if (pipe(pipefd) == -1) {
      perror("pipe");
      exit(1);
  }
  int read_end = pipefd[0];
  int write_end = pipefd[1];

  int n = fork(); //fork
  if (n < 0) {
      perror("fork");
      exit(1);
  } else if (n == 0) { // child process
      close(read_end);
      dup2(write_end, STDOUT_FILENO);
      close(write_end);
      execl("./validate", "validate", user_id, password, NULL);
      perror("execl");
      exit(1);
  } else { // parent process
      close(write_end);
      
      int status;
      pid_t child_pid = wait(&status);
      if (child_pid == -1) {
          perror("wait");
          exit(1);
      }
      
      if (WIFEXITED(status)) {
          int child_status = WEXITSTATUS(status);
          if (child_status == 0) {
              printf(SUCCESS);
          } else if (child_status == 2) {
              printf(INVALID);
          } else if (child_status == 3) {
              printf(NO_USER);
          }
      }

      close(read_end);
  }
  

  return 0;
}
