#include <check.h>
#include <errno.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>

#include "sem-wrapper/sem_wrapper.h"

START_TEST(test_sem_timedwait_wrapped)

    sem_t *sem = mmap(NULL,
                      sizeof(*sem),
                      PROT_READ | PROT_WRITE,
                      MAP_SHARED | MAP_ANONYMOUS,
                      -1,
                      0);
    ck_assert_ptr_ne(sem, MAP_FAILED);

    errno_t errnum;
    errnum = sem_init_wrapped(sem, 1, 0);
    ck_assert_int_eq(errnum, 0);

    pid_t pid = fork();
    if (pid == 0) {
        errnum = sem_post_wrapped(sem);
        if (errnum != EOK) {
            exit(1);
        }
        exit(0);
    }
    ck_assert_int_ge(pid, 0);

    int exit_status;
    pid_t child_pid;
    do {
        child_pid = waitpid(pid, &exit_status, 0);
    } while ((child_pid == -1) && (errno == EINTR));
    if (child_pid == -1) {
        perror("waitpid");
    }
    ck_assert_int_eq(child_pid, pid);
    ck_assert(WIFEXITED(exit_status));
    ck_assert_int_eq(WEXITSTATUS(exit_status), 0);

    int value = -1;
    errnum = sem_getvalue_wrapped(sem, &value);
    ck_assert_int_eq(errnum, EOK);
    ck_assert_int_eq(value, 1);

    struct timespec ts_interval = {.tv_sec = 2};
    errnum = sem_timedwait_wrapped(sem, &ts_interval);
    ck_assert_int_eq(errnum, EOK);

    value = -1;
    errnum = sem_getvalue_wrapped(sem, &value);
    ck_assert_int_eq(errnum, EOK);
    ck_assert_int_eq(value, 0);

    sem_destroy_wrapped(sem);

END_TEST

static Suite *test_suite_create(void)
{
    Suite *suite = suite_create("OS distribution bugs");
    TCase *tcase = tcase_create("libc");

    tcase_add_test(tcase, test_sem_timedwait_wrapped);

    suite_add_tcase(suite, tcase);

    return suite;
}

int main(int argc, char *argv[])
{
    int number_failed;

    Suite *suite = test_suite_create();
    SRunner *runner = srunner_create(suite);

    srunner_run_all(runner, CK_NORMAL);

    number_failed = srunner_ntests_failed(runner);

    srunner_free(runner);

    return number_failed;
}
