/*
 * pxadmin.c
 *
 * Copyright (C) 2006-2008  Joshua Hoblitt
 *
 * 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; version 2 of the License.
 *
 * 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
 * program; see the file COPYING. If not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

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

#include "pxtools.h"
#include "pxadmin.h"

bool createMode(pxConfig *config);
bool deleteMode(pxConfig *config);
static bool runMultipleStatments(pxConfig *config, const char *query);

int main(int argc, char **argv)
{
    psLibInit(NULL);

    pxConfig *config = pxAdminConfig(NULL, argc, argv);
    if (!config) {
        psError(PXTOOLS_ERR_CONFIG, false, "failed to configure");
        goto FAIL;
    }

    switch (config->mode) {
        case PXADMIN_MODE_RECREATE:
            if (!deleteMode(config)) {
                goto FAIL;
            }
            // fall through
        case PXADMIN_MODE_CREATE:
            if (!createMode(config)) {
                goto FAIL;
            }
            break;
        case PXADMIN_MODE_DELETE:
            if (!deleteMode(config)) {
                goto FAIL;
            }
            break;
        default:
            psAbort("invalid option (this should not happen)");
    }

    psFree(config);
    pmConfigDone();
    psLibFinalize();

    exit(EXIT_SUCCESS);

FAIL:
    psErrorStackPrint(stderr, "\n");

    int exit_status = pxerrorGetExitStatus();

    psFree(config);
    pmConfigDone();
    psLibFinalize();

    exit(exit_status);
}


bool createMode(pxConfig *config)
{
    PS_ASSERT_PTR_NON_NULL(config, false);

    psString query = pxDataGet("pxadmin_create_tables.sql");
    if (!query) {
        psError(PXTOOLS_ERR_DATA, false, "failed to retreive SQL statement");
        return false;
    }

    // BEGIN
    if (!psDBTransaction(config->dbh)) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        return false;
    }

    if (!runMultipleStatments(config, query)) {
        if (!psDBRollback(config->dbh)) {
                psError(PS_ERR_UNKNOWN, false, "database error");
        }
        psError(PS_ERR_UNKNOWN, false, "database error");
        psFree(query);
        return false;
    }
    psFree(query);

    // COMMIT
    if (!psDBCommit(config->dbh)) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        return false;
    }

    return true;
}


bool deleteMode(pxConfig *config)
{
    PS_ASSERT_PTR_NON_NULL(config, false);

    {
        char line[128], answer[128];

        psMetadataItem *name = pmConfigUserSite(config->modules, "DBNAME", PS_DATA_STRING);
        if (!name) {
            psError(PS_ERR_UNKNOWN, false, "Unable to determine database name.");
            return false;
        }
        psString dbName = name->data.str;

        fprintf(stdout, "*** delete the tables from database %s? ***\n", dbName);
        fprintf(stdout, "*** to delete the tables, answer YES, and give password ***\n");
        fprintf(stdout, "*** WARNING: this action is permanent ***\n\n");

        fprintf(stdout, "delete the tables (YES/[n]): ");
        if (!fgets(line, 128, stdin)) {
            psError(PS_ERR_IO, true, "Unable to read response.");
            return false;
        }
        sscanf(line, "%s", answer);
        if (strcmp (answer, "YES"))  {
            psError(PS_ERR_UNKNOWN, true, "tables NOT deleleted");
            return false;
        }

        fprintf(stdout, "enter dbh connection password: ");
        if (!fgets(line, 128, stdin)) {
            psError(PS_ERR_IO, true, "Unable to read response.");
            return false;
        }
        sscanf(line, "%s", answer);

        psMetadataItem *pass = pmConfigUserSite(config->modules, "DBPASSWORD", PS_DATA_STRING);
        if (!pass) {
            psError(PS_ERR_UNKNOWN, false, "Unable to determine database password.");
            return false;
        }
        psString dbPassword = pass->data.str;
        if (strcmp (answer, dbPassword)) {
            psError(PS_ERR_UNKNOWN, true, "invalid passwd - tables NOT deleleted");
            return false;
        }
    }

    psString query = pxDataGet("pxadmin_drop_tables.sql");
    if (!query) {
        psError(PXTOOLS_ERR_DATA, false, "failed to retreive SQL statement");
        return false;
    }

    // BEGIN
    if (!psDBTransaction(config->dbh)) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        return false;
    }

    if (!runMultipleStatments(config, query)) {
        if (!psDBRollback(config->dbh)) {
                psError(PS_ERR_UNKNOWN, false, "database error");
        }
        psError(PS_ERR_UNKNOWN, false, "database error");
        psFree(query);
        return false;
    }
    psFree(query);

    // COMMIT
    if (!psDBCommit(config->dbh)) {
        psError(PS_ERR_UNKNOWN, false, "database error");
        return false;
    }

    return true;
}


static bool runMultipleStatments(pxConfig *config, const char *query)
{
    PS_ASSERT_PTR_NON_NULL(config, false);
    PS_ASSERT_PTR_NON_NULL(query, false);

    // loop over all statements in string
    psList *statements = psStringSplit(query, ";", false);

    psString q = NULL;
    psListIterator *iter = psListIteratorAlloc(statements, PS_LIST_HEAD, false);
    while ((q = psListGetAndIncrement(iter))) {
        if (!p_psDBRunQuery(config->dbh, q)) {
            psError(PS_ERR_UNKNOWN, false, "database error");
            psFree(iter);
            psFree(statements);
            return false;
        }
    }
    psFree(iter);
    psFree(statements);

    return true;
}
