
#include <event2/event.h>
#include <event2/event_struct.h>

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <stdbool.h>

#define SIGPRI 0
#define TERMPRI 1

static struct event_base *base;
static bool run=true;
static struct event *t2=NULL;

static void
cbfunc(evutil_socket_t fd, short what, void *arg)
{
    fprintf(stderr, "CAUGHT SIGNAL\n");
    fflush(stderr);
#if 0
    event_base_loopbreak(base);
#endif
    run = false;
}

static void
die(const char *msg)
{
    fprintf(stderr, "%s\n", msg);
    fflush(stderr);
    exit(1);
}

static void
t2func(evutil_socket_t fd, short what, void *arg)
{
    struct event *t1 = (struct event*)arg;

    fprintf(stderr, "CAUGHT SECOND TERMINATION EVENT\n");
    fflush(stderr);
#if 0
    event_base_loopbreak(base);
#endif
    run = false;
}

static void
t1func(evutil_socket_t fd, short what, void *arg)
{
    struct event *t1 = (struct event*)arg;

    fprintf(stderr, "CAUGHT FIRST TERMINATION EVENT\n");
    fflush(stderr);
    t2 = (struct event*)malloc(sizeof(struct event));
    if (event_assign(t2, base, -1, EV_WRITE, t2func, &t2) < 0) {
        die("event_assign_term");
    }
    if (event_priority_set(t2, TERMPRI) < 0) {
        die("event_priority_set_term");
    }
    if (event_add(t2, NULL) < 0) {
        die("event_add_term");
    }
    fprintf(stderr, "SECOND TERMINATION EVENT DEFINED\n");
    fflush(stderr);
}

int
main(int argc, char **argv)
{
    struct event ev, t1;

    event_enable_debug_mode();

    fprintf(stderr, "Libevent %s\n", event_get_version());
    fflush(stderr);

    if (!(base = event_base_new()))
        die("event_base_new");
    if (event_base_priority_init(base, 8) < 0)
        die("event_base_priority_init");
    if (event_assign(&ev, base, SIGTERM, EV_SIGNAL|EV_PERSIST, cbfunc, NULL)<0)
        die("event_assign");
    if (event_priority_set(&ev, SIGPRI) < 0)
        die("event_priority_set");
    if (event_add(&ev, NULL) < 0)
        die("event_add");
    fprintf(stderr, "SIGNAL EVENT DEFINED\n");
    fflush(stderr);

    if (event_assign(&t1, base, -1, EV_WRITE, t1func, &t1) < 0) {
        die("event_assign_term");
    }
    if (event_priority_set(&t1, TERMPRI) < 0) {
        die("event_priority_set_term");
    }
    if (event_add(&t1, NULL) < 0) {
        die("event_add_term");
    }
    event_active(&t1, EV_WRITE, 1);
    fprintf(stderr, "FIRST TERMINATION EVENT DEFINED\n");
    fflush(stderr);

#if 0
    event_dispatch(base);
#endif
    while (run) {
        event_base_loop(base, EVLOOP_ONCE);
        if (NULL != t2) {
            event_active(t2, EV_WRITE, 1);
        }
    }

    fprintf(stderr, "EXITED LOOP - FREEING BASE\n");
    fflush(stderr);
    event_base_free(base);
    return 0;
}
