#include "settings.h"

#ifdef DOSQLLOGGING

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include "mysql_version.h"
#include "mysql.h"
#include "globals.h"

MYSQL sqlcon;
#define MAXSQLQUERYSIZE 5000
char *sqlquery;
char *pftmp;
char *pft2;

#endif

/* Opens SQL-Connection and creates tables. 0 == OK, everything else = error */
int sqlqinit(void) {
#ifdef DOSQLLOGGING
  printf("Initializing SQL...  ");
  mysql_init(&sqlcon);
  if ((sqlhost==NULL) || (sqlusername==NULL) || (sqlpassword==NULL) || (sqldb==NULL) || (sqllogtable==NULL) || (sqlport=0)) {
    printf("SQL Settings not set! Terminating!\n");
    return -1;
  }
  if (!mysql_real_connect(&sqlcon, sqlhost,sqlusername,sqlpassword,sqldb,sqlport,NULL,0)) {
    printf("Error connecting to mysql db.\n");
    return -1;
  }
  sqlquery=(char *)malloc(MAXSQLQUERYSIZE+1);
  pftmp=(char *)malloc(MAXSQLQUERYSIZE+1);
  pft2=(char *)malloc(MAXSQLQUERYSIZE+MAXSQLQUERYSIZE+1);
  if ((sqlquery==NULL) || (pftmp==NULL) || (pft2==NULL)) {
    printf("OUT OF MEMORY in sqlqinit()\n");
    return -2;
  }
  snprintf(sqlquery,MAXSQLQUERYSIZE,
    "CREATE TABLE %s (ID BIGINT DEFAULT '0' not null AUTO_INCREMENT, timestamp INT not null , typeofe INT , caller VARCHAR (100) not null , additionalinfo TEXT not null , PRIMARY KEY (ID, timestamp), UNIQUE (ID))",sqllogtable);
  sqlquery[MAXSQLQUERYSIZE]='\0';
  mysql_query(&sqlcon, sqlquery);
  printf("Done\n");
#endif
  return 0;
}

/* Puts an entry into the log.
   timestamp and unique ID get inserted automatically.
   t is the type of the log entry. For a complete list, see globals.h
   ca* is nick/user/host of who caused the entry
   formatstring is a printf-like formatstring, and it's of course followed
     by all needed parameters. this is what is put into "additionalinfo" in
     the log.
*/
void sqlqlog(int t, char *cani, char *caus, char *caho, const char *formatstring, ...) {
#ifdef DOSQLLOGGING
  va_list pa; char tmps2[256], tmps3[256], tmps4[256];
  if (sqlquery==NULL) { return; /* Just to be safe... */ }
  if ((strlen(cani)>100) || (strlen(caus)>100) || (strlen(caho)>100)) {
    return;
  }
  va_start(pa, formatstring);
  vsnprintf(pftmp,MAXSQLQUERYSIZE,formatstring,pa);
  va_end(pa);
  pftmp[MAXSQLQUERYSIZE]='\0';
  mysql_escape_string(pft2,pftmp,strlen(pftmp));
  mysql_escape_string(tmps2,cani,strlen(cani));
  mysql_escape_string(tmps3,caus,strlen(caus));
  mysql_escape_string(tmps4,caho,strlen(caho));
  snprintf(sqlquery,MAXSQLQUERYSIZE,"INSERT INTO %s VALUES('0','%ld','%d','%s!%s@%s','%s')",
    sqllogtable,(long)time(NULL),t,tmps2,tmps3,tmps4,pft2);
  sqlquery[MAXSQLQUERYSIZE]='\0';
  mysql_query(&sqlcon, sqlquery);
#endif
}

/* Closes the SQL connect again. */
void sqlqclose(void) {
#ifdef DOSQLLOGGING
  free(sqlquery);
  free(pftmp);
  mysql_close(&sqlcon);
#endif
}
