/*
 * gcc -o mycelspamdb `mysql_config --cflags` mycelspamdb.c `mysql_config --libs`
 */

#include <string.h>		/* for strdup() */
#include <my_global.h>
#include <my_sys.h>
#include <mysql.h>
#include <my_getopt.h>


#define SQLSCRIPT "deleteold.sql"
#define MYCNFSECT "mycelspamdb" /* [section] in ~/.my.cnf */

/* ---------------------- */
void runscript(MYSQL *conn);

static char *opt_host_name = NULL;		/* server host (default=localhost) */
static char *opt_user_name = NULL;		/* username (default=login name) */
static char *opt_password = NULL;		/* password (default=none) */
static unsigned int opt_port_num = 0;	/* port number (use built-in value) */
static char *opt_socket_name = NULL;	/* socket name (use built-in value) */
static char *opt_db_name = NULL;		/* database name (default=none) */
static unsigned int opt_flags = 0;		/* connection flags (none) */

static int ask_password = 0;			/* whether to solicit password */

static MYSQL *conn;						/* pointer to connection handler */

static const char *client_groups[] = { MYCNFSECT, "client", NULL };

static struct my_option my_opts[] =		/* option information structures */
{
	{"help", '?', "Display this help and exit",
	NULL, NULL, NULL,
	GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
	{"host", 'h', "Host to connect to",
	(gptr *) &opt_host_name, NULL, NULL,
	GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
	{"password", 'p', "Password",
	(gptr *) &opt_password, NULL, NULL,
	GET_STR_ALLOC, OPT_ARG, 0, 0, 0, 0, 0, 0},
	{"port", 'P', "Port number",
	(gptr *) &opt_port_num, NULL, NULL,
	GET_UINT, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
	{"socket", 'S', "Socket path",
	(gptr *) &opt_socket_name, NULL, NULL,
	GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
	{"user", 'u', "User name",
	(gptr *) &opt_user_name, NULL, NULL,
	GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
	{ NULL, 0, NULL, NULL, NULL, NULL, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0 }
};

/* #@ _PRINT_ERROR_ */
static void
print_error (MYSQL *conn, char *message)
{
	fprintf (stderr, "%s\n", message);
	if (conn != NULL)
	{
#if MYSQL_VERSION_ID >= 40101
		fprintf (stderr, "Error %u (%s): %s\n",
			mysql_errno (conn), mysql_sqlstate(conn), mysql_error (conn));
#else
		fprintf (stderr, "Error %u: %s\n",
			mysql_errno (conn), mysql_error (conn));
#endif
	}
}
/* #@ _PRINT_ERROR_ */

static my_bool
get_one_option (int optid, const struct my_option *opt, char *argument)
{
	switch (optid)
	{
	case '?':
		my_print_help (my_opts);	/* print help message */
		exit (0);
	case 'p':						/* password */
		if (!argument)				/* no value given; solicit it later */
			ask_password = 1;
		else						/* copy password, wipe out original */
		{
			opt_password = strdup (argument);
			if (opt_password == NULL)
			{
				print_error (NULL, "could not allocate password buffer");
				exit (1);
			}
			while (*argument)
				*argument++ = 'x';
			ask_password = 0;
		}
		break;
	}
	return (0);
}

int
main (int argc, char *argv[])
{
int opt_err;

	MY_INIT (argv[0]);
	load_defaults ("my", client_groups, &argc, &argv);

	if ((opt_err = handle_options (&argc, &argv, my_opts, get_one_option)))
		exit (opt_err);

	/* solicit password if necessary */
	if (ask_password)
		opt_password = get_tty_password (NULL);

	/* get database name if present on command line */
	if (argc > 0)
	{
		opt_db_name = argv[0];
		--argc; ++argv;
	}

fprintf(stderr, "--- OPTIONS ---\n");
fprintf(stderr, "opt_host_name: %s\n", opt_host_name);
fprintf(stderr, "opt_user_name: %s\n", opt_user_name);
fprintf(stderr, "opt_password: %s\n", opt_password);
fprintf(stderr, "opt_port_num: %d\n", opt_port_num);
fprintf(stderr, "opt_socket_name: %s\n", opt_socket_name);
fprintf(stderr, "opt_db_name: %s\n", opt_db_name);
fprintf(stderr, "opt_flags: %d\n", opt_flags);
fprintf(stderr, "----------------\n");




/* #@ _INIT_CONNECT_ */
	/* initialize connection handler */
	conn = mysql_init (NULL);
	if (conn == NULL)
	{
		print_error (NULL, "mysql_init() failed (probably out of memory)");
		exit (1);
	}

	/* connect to server */
	if (mysql_real_connect (conn, opt_host_name, opt_user_name, opt_password,
			opt_db_name, opt_port_num, opt_socket_name, opt_flags) == NULL)
	{
		print_error (conn, "mysql_real_connect() failed");
		mysql_close (conn);
		exit (1);
	}
/* #@ _INIT_CONNECT_ */

	/* ... issue statements and process results here ... */
	runscript(conn);

	/* disconnect from server */
	mysql_close (conn);
	exit (0);
}

void runscript(MYSQL *conn)
{
	char buf[65535];
	size_t bytes;
	int remain=0;
	FILE* fp = fopen(SQLSCRIPT, "r");
	if (!fp) {
		perror("Opening sqlscript '" SQLSCRIPT "' failed");
		return;
	}

	while (fgets(buf, sizeof(buf), fp)) {
		int err;
		
		/* strip of newline */
		if (buf[strlen(buf)-1] == '\n')
			buf[strlen(buf)-1] = '\0';

		printf("Q: %s\n", buf);
		err = mysql_query(conn, buf);
		if (err) {
			print_error (conn, "Query FAILED!");
		} else {
			printf("OK\n");
		}
	}
}
