#define _POSIX_C_SOURCE 200809L
#define _XOPEN_SOURCE 500
#include <sys/wait.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <termios.h>
#include <unistd.h>

void pexit(const char *fn)
{
    perror(fn);
    exit(-1);
}

void allow_login();
void open_tty();

int main()
{
    pid_t p = fork();
    if (p < 0)
        pexit("fork");
    else if (p != 0)
    {
        printf("Fork succeeded, parent exiting...\n");
        exit(0);
    }

    signal(SIGHUP, SIG_IGN);

    pid_t session_id = setsid();
    if (session_id < 0)
        pexit("setsid");

    while (1)
    {
        open_tty();
        allow_login();
    }

    return 0;
}

void open_tty()
{
    close(STDOUT_FILENO);
    close(STDERR_FILENO);
    close(STDIN_FILENO);

    if (open("/dev/tty8", O_RDWR, 0) != 0)
        exit(-2);

    dup2(STDIN_FILENO, STDOUT_FILENO);
    dup2(STDIN_FILENO, STDERR_FILENO);

    tcsetpgrp(STDIN_FILENO, getpid());
    tcflush(STDIN_FILENO, TCIOFLUSH);
}

void allow_login()
{
    system("tput clear");
    printf("Got to allow_login!\n");
    pid_t p = fork();

    if (p == 0)
    {
        setpgid(getpid(), getpid());
        tcsetpgrp(STDIN_FILENO, p);
        execl("/bin/login", "login", NULL);
    }
    else
    {
        int wstatus;
        waitpid(p, &wstatus, WUNTRACED);

        if (WIFSTOPPED(wstatus))
        {
            tcsetpgrp(STDIN_FILENO, p);
            kill(p, SIGCONT);
        }

        waitpid(p, &wstatus, 0);
        tcsetpgrp(STDIN_FILENO, getpgrp());

        system("tput clear");
    }
}

