#define _POSIX_C_SOURCE 200809L
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

enum { WIDTH = 30, HEIGHT = 12 };
static volatile sig_atomic_t stopped;

static void stop_animation(int signal_number)
{
    (void)signal_number;
    stopped = 1;
}

static int argument(const char *text, int maximum)
{
    char *end;
    errno = 0;
    long value = strtol(text, &end, 10);
    if (errno || !*text || *end || value < 0 || value > maximum) return -1;
    return (int)value;
}

static void delay_ms(int milliseconds)
{
    struct timespec left = {milliseconds / 1000, (milliseconds % 1000) * 1000000L};
    while (!stopped && nanosleep(&left, &left) < 0 && errno == EINTR) {}
}

static void install_controls(void)
{
    struct sigaction action = {0};
    action.sa_handler = stop_animation;
    sigemptyset(&action.sa_mask);
    if (sigaction(SIGINT, &action, NULL) || sigaction(SIGTERM, &action, NULL)) {
        perror("signal setup");
        exit(1);
    }
    fputs("\033[?25l", stdout);
}

static void finish(void)
{
    fputs("\033[0m\033[2J\033[H\033[?25h", stdout);
    fflush(stdout);
}

int main(int argc, char **argv)
{
    int frames = argc >= 2 ? argument(argv[1], 10000) : 0;
    int delay = argc >= 3 ? argument(argv[2], 1000) : 100;
    if (argc > 3 || frames < 0 || delay < 0) {
        fputs("Usage: terminal [frames 0-10000] [delay_ms 0-1000]\n", stderr);
        return 2;
    }
    install_controls();
    int row = 1, direction = 1;
    for (unsigned frame = 0; !stopped && (!frames || frame < (unsigned)frames); ++frame) {
        printf("\033[2J\033[%d;4H\033[36m============", row);
        fflush(stdout);
        delay_ms(delay);
        if (row + direction < 1 || row + direction >= HEIGHT /* TODO: inspect the last row */) direction = -direction;
        row += direction;
    }
    finish();
    return 0;
}
