/**
* Test case for MDEV-9195
*
* This test mimics MaxScale's use of the embedded library.
*/

#define _XOPEN_SOURCE 700
#include <my_config.h>
#include <ftw.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <time.h>
#include <getopt.h>
#include <stdlib.h>
#include <unistd.h>
#include <mysql.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <execinfo.h>
#include <sys/wait.h>
#include <sys/prctl.h>
#include <sys/file.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <pthread.h>
#include <linux/limits.h>

#define TEST_DATADIR "--datadir=."
#define TEST_LANGUAGE "--language=."
#define TEST_THREADS 1

static char* server_options[] ={
    (char*)"MDEV-9195",
    (char*)"--no-defaults",
    (char*)TEST_DATADIR,
    (char*)TEST_LANGUAGE,
    (char*)"--skip-innodb",
    (char*)"--default-storage-engine=myisam",
    NULL
};
static char* server_groups[] = {
    (char*)"embedded",
    (char*)"server",
    (char*)"server",
    NULL
};

const int num_elements = (sizeof(server_options) / sizeof(char *)) - 1;

void* test_thr(void *data);
void stop();

int main(int argc, char **argv)
{

    int thread_count = TEST_THREADS;
    
    if(argc > 1 && (thread_count = atoi(argv[1])) < 1)
    {
        printf("Bad thread count argument: %s\n", argv[1]);
        return 1;
    }

    pthread_t threads[thread_count];
    char buf[PATH_MAX + 1];
    char *cwd = getcwd(buf, sizeof(buf));
    setenv("MYSQL_HOME", cwd, 1);

    if(mysql_server_init(num_elements, server_options, server_groups))
    {
        printf("failed to initialize the embedded library\n");
        return 1;
    }

    printf("Creating %d threads\n", thread_count);

    for(int i = 0; i < thread_count; i++)
    {
        pthread_create(&threads[i], NULL, test_thr, NULL);
    }
    printf("Threads running for 300 seconds.\n");
    sleep(300);
    stop();

    for(int i = 0; i < thread_count; i++)
    {
        pthread_join(threads[i], NULL);
    }

    mysql_library_end();
    return 0;
}
