#include <string.h>
#include <stdlib.h>
#include <mysql.h>

/*
 * gcc -Wall -fPIC -I/usr/include/mysql -I. -shared FuncionesUTN.c -o /usr/lib64/mysql/plugin/FuncionesUTN.so
 */

/*
 * DROP FUNCTION IF EXISTS `UTN_EnvioCorreo`;
 * CREATE FUNCTION `UTN_EnvioCorreo` RETURNS INT SONAME 'FuncionesUTN.so';
 * SELECT `UTN_EnvioCorreo`('pruebas@utn.ac.cr', 'dvillalobos@utn.ac.cr', 'Asunto desde MariaDB', 'Cuerpo del mensaje');
 */

/*
 * Ejemplo: https://github.com/twitter/mysql/blob/master/sql/udf_example.c
 */

/*
 * Inicio UTN_EnvioCorreo
 */

my_bool UTN_EnvioCorreo_init(UDF_INIT *initid, UDF_ARGS *args, char *message) {
  
  if(args->arg_count == 4
    && args->arg_type[0] == STRING_RESULT
    && args->arg_type[1] == STRING_RESULT
    && args->arg_type[2] == STRING_RESULT
    && args->arg_type[3] == STRING_RESULT
  ) {
    return 0;
  } else {
    strcpy(message, "Se esperan 4 parámetos de tipo texto: De, Para, Asunto y Mensaje.");
    return 1;
  }
}

void UTN_EnvioCorreo_deinit(UDF_INIT *initid) {
  
}

void UTN_EnvioCorreo_reset(UDF_INIT* initid, UDF_ARGS* args, char* is_null, char *error) {
  
}

void UTN_EnvioCorreo_clear(UDF_INIT* initid, char* is_null, char *error) {
  
}

void UTN_EnvioCorreo_add(UDF_INIT* initid, UDF_ARGS* args, char* is_null, char *error) {
  
}

my_ulonglong UTN_EnvioCorreo(UDF_INIT *initid, UDF_ARGS *args, char *is_null, char *error) {
  
  char comando[1000];
  strcpy(comando, "echo ");
  strcat(comando, args->args[0]);
  strcat(comando, " ");
  strcat(comando, args->args[1]);
  strcat(comando, " ");
  strcat(comando, args->args[2]);
  strcat(comando, " ");
  strcat(comando, args->args[3]);
  strcat(comando, " >> /tmp/UNT_MariaDB_Bitacora");
  return system(comando);
}

/*
 * Final UTN_EnvioCorreo
 */
