/*
 * Test case originally extract from:
 *
 * authmilter (c) 2013 Vesa-Matti J. Kari <vmkari@cc.helsinki.fi>
 *
 * License: GPLv2
 *
 * v0.3alpha - 2013-xx-yy
 *
 */
#include <stdio.h>
#include <stdlib.h>

#include <pthread.h>

#include <libpq-fe.h>

char *connstr = "";

int test_connect(int threadid)
{
	PGconn *pg_conn;
	ConnStatusType cst;

	pg_conn = PQconnectdb(connstr);

	cst = PQstatus(pg_conn);
	if (cst != CONNECTION_OK) {
		char *pg_conn_status;
		switch(cst)
		{
			case CONNECTION_BAD:
				pg_conn_status = "CONNECTION_BAD";
				break;
			default:
				pg_conn_status = "UNKNOWN_STATUS";
		}
		printf("%d: could not connect to database server: %d: %s\n",
			   threadid, cst, pg_conn_status);
		return 1;
	}
	printf("%d: DEBUG: database connection established\n", threadid);

	printf("%d: DEBUG: about to call PQfinish()\n", threadid);
	PQfinish(pg_conn);

	return 0;
}

void *run_thread(void *arg)
{
	int threadid = *((int *) arg);

	for(;;)
		test_connect(threadid);
}

static int one = 1;
static int two = 2;

int main(int argc, char **argv)
{
	pthread_t t1;
	pthread_t t2;
	int s;

	if (argc > 1)
		connstr = argv[1];

	s = pthread_create(&t1, NULL, &run_thread, &one);
	s = pthread_create(&t2, NULL, &run_thread, &two);

	sleep(20);
}
