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

#define MAXLINE 256

#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];

    if (fgets(user_id, MAXLINE, stdin) == NULL) {
        perror("fgets");
        exit(1);
    }
    if (fgets(password, MAXLINE, stdin) == NULL) {
        perror("fgets");
        exit(1);
    }

    if (strlen(password) > 9) {
        perror("password too long");
        exit(1);
    }

    if (strlen(user_id) > 9) {
        perror("user id too long");
        exit(1);
    }

    int fd[2];

    if (pipe(fd) == -1) {
        perror("pipe");
        exit(1);
    }

    int r = fork();

    if (r == 0) {
        close(fd[1]);
        if (dup2(fd[0], fileno(stdin)) == -1) {
            perror("dup2");
            exit(1);
        }
        execl("./validate", "validate", NULL);
    } else if (r > 0) {
        close(fd[0]);
        write(fd[1], user_id, strlen(user_id));
        write(fd[1], password, strlen(password));

        int status;
        while (wait(&status) > 0)
            ;

        if (WIFEXITED(status)) {
            if (WEXITSTATUS(status) == 1) {
                perror("validate");
                exit(1);
            } else if (WEXITSTATUS(status) == 0) {
                printf("%s\n", SUCCESS);
            } else if (WEXITSTATUS(status) == 2) {
                printf("%s\n", INVALID);
            } else if (WEXITSTATUS(status) == 3) {
                printf("%s\n", NO_USER);
            }
        } else {
            perror("validate");
            exit(1);
        }
    } else {
        perror("fork");
        exit(1);
    }
    return 0;
}