/*
 * Kangaroo Punch MultiPlayer Game Server Mark II
 * Copyright (C) 2020-2021  Scott Duensing
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 */


#include <mysql.h>
#include <pthread.h>
#include <crypt.h>

#include "array.h"
#include "database.h"


// ***TODO*** Left/Right trim whitespace from returned strings?


#define STATEMENT_MAX  2048


static MYSQL           *_sql   = NULL;
static pthread_mutex_t  _mutex = PTHREAD_MUTEX_INITIALIZER;


uint8_t dbConnect(char *host, uint16_t port, char *database, char *user, char *password) {
	uint8_t reconnect = 1;

	if (_sql == NULL) {
		_sql = mysql_init(NULL);
		mysql_options(_sql, MYSQL_OPT_RECONNECT, (const void *)&reconnect);
		if (mysql_real_connect(_sql, host, user, password, database, port, NULL, 0) == NULL) {
			logWrite("dbConnect:  %s\n", mysql_error(_sql));
			return FAIL;
		}
		if (pthread_mutex_init(&_mutex, NULL)) {
			logWrite("dbConnect:  SQL mutex creation failed.\n");
			return FAIL;
		}
		return SUCCESS;
	}
	return FAIL;
}


uint8_t dbDisconnect(void) {
	if (_sql) {
		 mysql_close(_sql);
		 _sql = NULL;
		 pthread_mutex_destroy(&_mutex);
		 return SUCCESS;
	}

	return FAIL;
}


uint8_t dbFileRealPathGet(char *vpath, char *value, uint32_t max) {
	char       statement[STATEMENT_MAX];
	char      *p      = statement;
	MYSQL_RES *result = NULL;
	MYSQL_ROW  row;
	int        count;

	pthread_mutex_lock(&_mutex);

	if (!_sql) {
		pthread_mutex_unlock(&_mutex);
		return FAIL;
	}

	p += sprintf(p, "SELECT realPath FROM files WHERE virtualPath='");
	p += mysql_real_escape_string(_sql, p, vpath, strlen(vpath));
	p += sprintf(p, "'");
	if (mysql_real_query(_sql, statement, p - statement) != 0) {
		logWrite("dbFileRealPathGet:  %s\n", mysql_error(_sql));
		pthread_mutex_unlock(&_mutex);
		return FAIL;
	}

	result = mysql_store_result(_sql);
	count = mysql_num_rows(result);
	if (count != 1) {
		logWrite("dbFileRealPathGet:  Wrong number of rows returned:  %d.\n", count);
		mysql_free_result(result);
		pthread_mutex_unlock(&_mutex);
		return FAIL;
	}

	if ((row = mysql_fetch_row(result)) == NULL) {
		logWrite("dbFileRealPathGet:  %s\n", mysql_error(_sql));
		pthread_mutex_unlock(&_mutex);
		return FAIL;
	}

	strncpy(value, row[0], max);

	mysql_free_result(result);

	pthread_mutex_unlock(&_mutex);

	return SUCCESS;
}


uint8_t dbFileSha256Get(char *vpath, char *value, uint32_t max) {
	char       statement[STATEMENT_MAX];
	char      *p      = statement;
	MYSQL_RES *result = NULL;
	MYSQL_ROW  row;
	int        count;

	pthread_mutex_lock(&_mutex);

	if (!_sql) {
		pthread_mutex_unlock(&_mutex);
		return FAIL;
	}

	p += sprintf(p, "SELECT sha256 FROM files WHERE virtualPath='");
	p += mysql_real_escape_string(_sql, p, vpath, strlen(vpath));
	p += sprintf(p, "'");
	if (mysql_real_query(_sql, statement, p - statement) != 0) {
		logWrite("dbFileSha256Get:  %s\n", mysql_error(_sql));
		pthread_mutex_unlock(&_mutex);
		return FAIL;
	}

	result = mysql_store_result(_sql);
	count = mysql_num_rows(result);
	if (count != 1) {
		logWrite("dbFileSha256Get:  Wrong number of rows returned:  %d.\n", count);
		mysql_free_result(result);
		pthread_mutex_unlock(&_mutex);
		return FAIL;
	}

	if ((row = mysql_fetch_row(result)) == NULL) {
		logWrite("dbFileSha256Get:  %s\n", mysql_error(_sql));
		pthread_mutex_unlock(&_mutex);
		return FAIL;
	}

	strncpy(value, row[0], max);

	mysql_free_result(result);

	pthread_mutex_unlock(&_mutex);

	return SUCCESS;
}


uint8_t dbSettingsStringGet(char *host, char *key, char *value, uint32_t max) {
	char       statement[STATEMENT_MAX];
	char      *p      = statement;
	MYSQL_RES *result = NULL;
	MYSQL_ROW  row;
	int        count;

	pthread_mutex_lock(&_mutex);

	if (!_sql) {
		pthread_mutex_unlock(&_mutex);
		return FAIL;
	}

	p += sprintf(p, "SELECT data FROM config WHERE name='");
	p += mysql_real_escape_string(_sql, p, key, strlen(key));
	p += sprintf(p, "' AND host='");
	p += mysql_real_escape_string(_sql, p, host, strlen(host));
	p += sprintf(p, "'");
	if (mysql_real_query(_sql, statement, p - statement) != 0) {
		logWrite("dbConfigValueGet:  %s\n", mysql_error(_sql));
		pthread_mutex_unlock(&_mutex);
		return FAIL;
	}

	result = mysql_store_result(_sql);
	count = mysql_num_rows(result);
	if (count != 1) {
		logWrite("dbConfigValueGet:  Too many rows returned:  %d.\n", count);
		mysql_free_result(result);
		pthread_mutex_unlock(&_mutex);
		return FAIL;
	}

	if ((row = mysql_fetch_row(result)) == NULL) {
		logWrite("dbConfigValueGet:  %s\n", mysql_error(_sql));
		pthread_mutex_unlock(&_mutex);
		return FAIL;
	}

	strncpy(value, row[0], max);

	mysql_free_result(result);

	pthread_mutex_unlock(&_mutex);

	return SUCCESS;
}


uint8_t dbSettingsValueGet(char *host, char *key, int32_t *value) {
	char temp[DB_CONFIG_ITEM_SIZE] = { 0 };

	if (dbSettingsStringGet(host, key, temp, DB_CONFIG_ITEM_SIZE) == FAIL) return FAIL;

	*value = atoi(temp);

	return SUCCESS;
}


uint8_t dbTableGet(char *which, DBTableT ***table) {
	char       statement[STATEMENT_MAX];
	char      *p      = statement;
	MYSQL_RES *result = NULL;
	MYSQL_ROW  row;
	int        count;
	DBTableT  *record = NULL;

	pthread_mutex_lock(&_mutex);

	if (!_sql) {
		pthread_mutex_unlock(&_mutex);
		return FAIL;
	}

	p += sprintf(p, "SELECT name, data FROM ");
	p += mysql_real_escape_string(_sql, p, which, strlen(which));
	if (mysql_real_query(_sql, statement, p - statement) != 0) {
		logWrite("dbTableGet:  %s\n", mysql_error(_sql));
		pthread_mutex_unlock(&_mutex);
		return FAIL;
	}

	result = mysql_store_result(_sql);
	for (count = 0; count < (int)mysql_num_rows(result); count++) {
		if ((row = mysql_fetch_row(result)) == NULL) {
			logWrite("dbTableGet:  %s\n", mysql_error(_sql));
			pthread_mutex_unlock(&_mutex);
			return FAIL;
		}

		NEW(DBTableT, record);
		record->name = strdup(row[0]);
		record->data = strdup(row[1]);
		arrput(*table, record);
	}

	mysql_free_result(result);

	pthread_mutex_unlock(&_mutex);

	return SUCCESS;
}


uint8_t dbUserCreate(char *first, char *last, char *user, char *pass, char *email) {
	char  statement[STATEMENT_MAX];
	char *p    = statement;
	char *hash = NULL;
	char *salt = NULL;

	pthread_mutex_lock(&_mutex);

	if (!_sql) {
		pthread_mutex_unlock(&_mutex);
		return FAIL;
	}

	// Not thread safe.  Protected by SQL _mutex.
	salt = crypt_gensalt(0, 0, 0, 0);
	hash = crypt(pass, salt);

	// We don't pass 'enabled' into the database and instead rely on the default value.
	p += sprintf(p, "INSERT INTO users (first, last, user, pass, email) VALUES ('");
	p += mysql_real_escape_string(_sql, p, first, strlen(first));
	p += sprintf(p, "', '");
	p += mysql_real_escape_string(_sql, p, last, strlen(last));
	p += sprintf(p, "', '");
	p += mysql_real_escape_string(_sql, p, user, strlen(user));
	p += sprintf(p, "', '");
	p += mysql_real_escape_string(_sql, p, hash, strlen(hash));
	p += sprintf(p, "', '");
	p += mysql_real_escape_string(_sql, p, email, strlen(email));
	p += sprintf(p, "')");
	if (mysql_real_query(_sql, statement, p - statement) != 0) {
		logWrite("dbUserCreate:  %s\n", mysql_error(_sql));
		pthread_mutex_unlock(&_mutex);
		return FAIL;
	}

	pthread_mutex_unlock(&_mutex);

	return SUCCESS;
}


uint8_t dbUserEmailExists(char *email) {
	char       statement[STATEMENT_MAX];
	char      *p      = statement;
	MYSQL_RES *result = NULL;
	int32_t    count  = 0;
	uint8_t    status = FAIL;

	pthread_mutex_lock(&_mutex);

	if (!_sql) {
		pthread_mutex_unlock(&_mutex);
		return FAIL;
	}

	p += sprintf(p, "SELECT id FROM users WHERE email='");
	p += mysql_real_escape_string(_sql, p, email, strlen(email));
	p += sprintf(p, "'");
	if (mysql_real_query(_sql, statement, p - statement) != 0) {
		logWrite("dbUserEmailExists:  %s\n", mysql_error(_sql));
		pthread_mutex_unlock(&_mutex);
		return FAIL;
	}

	result = mysql_store_result(_sql);
	count = mysql_num_rows(result);

	if (count == 1) status = SUCCESS;
	if ((count != 1) && (count != 0)) logWrite("dbUserEmailExists:  Invalid number of rows returned:  %d.\n", count);

	mysql_free_result(result);
	pthread_mutex_unlock(&_mutex);

	return status;
}


uint8_t dbUserLogin(char *user, char *password) {
	char       statement[STATEMENT_MAX];
	char      *p      = statement;
	MYSQL_RES *result = NULL;
	MYSQL_ROW  row;
	int        count;
	uint8_t    status = FAIL;

	pthread_mutex_lock(&_mutex);

	if (!_sql) {
		pthread_mutex_unlock(&_mutex);
		return FAIL;
	}

	p += sprintf(p, "SELECT pass FROM users WHERE user='");
	p += mysql_real_escape_string(_sql, p, user, strlen(user));
	p += sprintf(p, "' AND enabled=1");
	if (mysql_real_query(_sql, statement, p - statement) != 0) {
		logWrite("dbUserLogin:  %s\n", mysql_error(_sql));
		pthread_mutex_unlock(&_mutex);
		return FAIL;
	}

	result = mysql_store_result(_sql);
	count = mysql_num_rows(result);
	if (count != 1) {
		//logWrite("dbUserLogin:  Too many rows returned:  %d.\n", count);
		mysql_free_result(result);
		pthread_mutex_unlock(&_mutex);
		return FAIL;
	}

	if ((row = mysql_fetch_row(result)) == NULL) {
		logWrite("dbUserLogin:  %s\n", mysql_error(_sql));
		pthread_mutex_unlock(&_mutex);
		return FAIL;
	}

	// Not thread safe.  Protected by SQL _mutex.
	p = crypt(password, row[0]);
	if (strcmp(p, row[0]) == 0) status = SUCCESS;

	mysql_free_result(result);

	pthread_mutex_unlock(&_mutex);

	return status;
}


uint8_t dbUserNameExists(char *user) {
	char       statement[STATEMENT_MAX];
	char      *p      = statement;
	MYSQL_RES *result = NULL;
	int32_t    count  = 0;
	uint8_t    status = FAIL;

	pthread_mutex_lock(&_mutex);

	if (!_sql) {
		pthread_mutex_unlock(&_mutex);
		return FAIL;
	}

	p += sprintf(p, "SELECT id FROM users WHERE user='");
	p += mysql_real_escape_string(_sql, p, user, strlen(user));
	p += sprintf(p, "'");
	if (mysql_real_query(_sql, statement, p - statement) != 0) {
		logWrite("dbUserNameExists:  %s\n", mysql_error(_sql));
		pthread_mutex_unlock(&_mutex);
		return FAIL;
	}

	result = mysql_store_result(_sql);
	count = mysql_num_rows(result);

	if (count == 1) status = SUCCESS;
	if ((count != 1) && (count != 0)) logWrite("dbUserNameExists:  Invalid number of rows returned:  %d.\n", count);

	mysql_free_result(result);
	pthread_mutex_unlock(&_mutex);

	return status;
}



