/*
 * dsyslog - a dumb syslog (e.g. syslog for people who have a clue)
 * Copyright (c) 2008 Jeff Katz <kraln@kraln.com>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice is present in all copies.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "dsyslog.h"
#include <libpq-fe.h>
#include <time.h>

static void
output_postgres_destructor(dsyslog_output_t *output)
{
	_ENTER;

	PQfinish((PGconn *)(output->opaque));

	_LEAVE;
}

static void
output_postgres_handler(dsyslog_event_t *event, dsyslog_output_t *output)
{
	PGconn *conn;
	PGresult *res;	
	gchar *conninfo;

	_ENTER;

	if (!output->dbuser || !output->dbpass || !output->dbname || !output->dbhost) {
		_LEAVE;
	}
                                                                                 	
 	conninfo = g_strdup_printf("host=%s dbname=%s user=%s password=%s", output->dbhost,
 		output->dbname, output->dbuser, output->dbpass);      
 		
 		_DEBUG("Connection String: %s", conninfo);

	if (!output->opaque) {
		
    conn = PQconnectdb(conninfo);

    /* Check to see that the backend connection was successfully made */
    if (PQstatus(conn) != CONNECTION_OK)
    {
        _ERROR("Connection to database failed: %s", PQerrorMessage(conn));
        PQfinish(conn);
        _LEAVE;
    }

		/* at this point, we're going to prepare the statement to put into the database, because we're going to be
		   calling it several times. this also allows us to not have to worry about sanitizing inputs */
		   
		res = PQprepare(conn, "logstmt", "INSERT INTO `log` (logcode, timestamp, datestamp, source, program, message) VALUES ($1, $2, $3, $4, $5, $6)", 0, NULL);
		
		if (PQresultStatus(res) != PGRES_COMMAND_OK)
		{
			 _ERROR("Preparing log statement failed: %s", PQerrorMessage(conn));
        PQfinish(conn);
        _LEAVE;
		}
		
		PQclear(res);
		/* save our connection pointer */
		output->opaque = conn;
		output->destructor = output_postgres_destructor;
	}

	g_free(conninfo);
	conn = (PGconn *)(output->opaque);
	char** charPtrs = malloc(sizeof(char*) * 6);
	char* cTime = (char*) malloc(100); 
	char* cLogCode = (char*) malloc(100);

	sprintf(cLogCode, "%d", event->logcode);
	sprintf(cTime, "%ld", time(NULL));

	charPtrs[0] = cLogCode;
	charPtrs[1] = cTime;
	charPtrs[2] = event->datestamp;
	charPtrs[3] = event->source;
	charPtrs[4] = event->program;
	charPtrs[5] = event->message;

  // perform the query
	res = PQexecPrepared (conn, "logstmt", 6, (const char* const*)charPtrs, NULL, NULL, 0);
	if (PQresultStatus(res) != PGRES_COMMAND_OK)
	{
		 _ERROR("Entering log statement failed: %s", PQerrorMessage(conn));
     PQfinish(conn);
	}

	PQclear(res);
	free(cTime);
	free(cLogCode);
	free(charPtrs);
	_LEAVE;
}

void
_modinit(void)
{
	_ENTER;

	dsyslog_output_type_register("postgres", output_postgres_handler);

	_LEAVE;
}

void
_modfini(void)
{
	_ENTER;

	dsyslog_output_type_unregister("postgres");

	_LEAVE;
}
