/*
 * pubtool.c
 *
 * Copyright (C) 2008
 *
 * 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 <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <inttypes.h>

#include "pxtools.h"
#include "pxdata.h"
#include "pubtool.h"

static bool defineclientMode(pxConfig *config);
static bool definerunMode(pxConfig *config);
static bool pendingMode(pxConfig *config);
static bool addMode(pxConfig *config);
static bool revertMode(pxConfig *config);

# define MODECASE(caseName, func) \
    case caseName: \
    if (!func(config)) { \
        goto FAIL; \
    } \
    break;


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

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

    switch (config->mode) {
        MODECASE(PUBTOOL_MODE_DEFINECLIENT, defineclientMode);
        MODECASE(PUBTOOL_MODE_DEFINERUN, definerunMode);
        MODECASE(PUBTOOL_MODE_PENDING, pendingMode);
        MODECASE(PUBTOOL_MODE_ADD, addMode);
        MODECASE(PUBTOOL_MODE_REVERT, revertMode);
      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);
}

static bool defineclientMode(pxConfig *config)
{
    PS_ASSERT_PTR_NON_NULL(config, false);

    // required
    PXOPT_LOOKUP_STR(product, config->args, "-product",  true, false);
    PXOPT_LOOKUP_STR(stage, config->args, "-stage", true, false);
    PXOPT_LOOKUP_STR(workdir, config->args, "-workdir",  true, false);

    // optional
    PXOPT_LOOKUP_STR(comment, config->args, "-comment",  false, false);

    if (!publishClientInsert(config->dbh, 0, product, stage, workdir, comment)) {
        psError(PS_ERR_UNKNOWN, false, "Database error");
        return false;
    }

    return true;
}

static bool definerunMode(pxConfig *config)
{
    PS_ASSERT_PTR_NON_NULL(config, false);

    psMetadata *where = psMetadataAlloc(); // WHERE conditions

    // required

    // optional
    PXOPT_COPY_S64(config->args, where, "-client_id", "client_id", "==");
    PXOPT_COPY_STR(config->args, where, "-label", "label", "==");

    PXOPT_LOOKUP_STR(label, config->args, "-label", false, false);

    psString query = pxDataGet("pubtool_definerun.sql"); // Query to run
    if (!query) {
        psError(PXTOOLS_ERR_DATA, false, "Failed to retreive SQL statement");
        psFree(where);
        return false;
    }

    if (!psDBTransaction(config->dbh)) {
        psError(PS_ERR_UNKNOWN, false, "Database error");
        psFree(where);
        return false;
    }

    psString whereClause = psStringCopy(""); // Additional constraints to add to query
    if (psListLength(where->list)) {
        psString clause = psDBGenerateWhereConditionSQL(where, NULL);
        psStringAppend(&whereClause, "\n AND %s", clause);
        psFree(clause);
    }
    psFree(where);

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

    psArray *output = p_psDBFetchResult(config->dbh); // Output of SELECT statement
    if (!output) {
        psError(PS_ERR_UNKNOWN, false, "Database error");
        if (!psDBRollback(config->dbh)) {
            psError(PS_ERR_UNKNOWN, false, "Database error");
        }
        return false;
    }
    if (!psArrayLength(output)) {
        psTrace("pubtool", PS_LOG_INFO, "No rows found");
        psFree(output);
        return true;
    }

    for (int i = 0; i < output->n; i++) {
        psMetadata *row = output->data[i]; // Row of interest
        psS64 client = psMetadataLookupS64(NULL, row, "client_id"); // Client identifier
        psS64 stage = psMetadataLookupS64(NULL, row, "stage_id");   // Stage identifier

        if (!publishRunInsert(config->dbh, 0, client, stage, label, "new")) {
            psError(PS_ERR_UNKNOWN, false, "Unable to add fileset");
            psFree(output);
            if (!psDBRollback(config->dbh)) {
                psError(PS_ERR_UNKNOWN, false, "Database error");
            }
            return false;
        }
    }
    psFree(output);

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

    return true;
}

static bool pendingMode(pxConfig *config)
{
    PS_ASSERT_PTR_NON_NULL(config, false);

    psMetadata *where = psMetadataAlloc(); // WHERE conditions

    // required
    PXOPT_COPY_STR(config->args, where, "-client_id", "publishClient.client_id", "==");
    PXOPT_COPY_STR(config->args, where, "-stage", "publishClient.stage", "==");
    PXOPT_COPY_STR(config->args, where, "-comment", "publishClient.comment", "LIKE");
    PXOPT_COPY_STR(config->args, where, "-label", "publishRun.label", "==");

    // optional
    PXOPT_LOOKUP_U64(limit, config->args, "-limit", false, false);
    PXOPT_LOOKUP_BOOL(simple, config->args, "-simple", false);

    psString query = pxDataGet("pubtool_pending.sql");
    if (!query) {
        psError(PXTOOLS_ERR_DATA, false, "Failed to retreive SQL statement");
        psFree(where);
        return false;
    }

    psString whereClause = psStringCopy(""); // WHERE conditions to add
    if (psListLength(where->list)) {
        psString clause = psDBGenerateWhereConditionSQL(where, NULL);
        psStringAppend(&whereClause, "\nAND %s", clause);
        psFree(clause);
    }
    psFree(where);

    if (limit) {
        psString limitString = psDBGenerateLimitSQL(limit);
        psStringAppend(&query, " %s", limitString);
        psFree(limitString);
    }

    if (!p_psDBRunQueryF(config->dbh, query, whereClause, whereClause)) {
        psError(PS_ERR_UNKNOWN, false, "Database error");
        psFree(whereClause);
        psFree(query);
        return false;
    }
    psFree(whereClause);
    psFree(query);

    psArray *output = p_psDBFetchResult(config->dbh);
    if (!output) {
        psError(PS_ERR_UNKNOWN, false, "Database error");
        return false;
    }
    if (!psArrayLength(output)) {
        psTrace("pubtool", PS_LOG_INFO, "No rows found");
        psFree(output);
        return true;
    }
    if (!ippdbPrintMetadatas(stdout, output, "publishRun", !simple)) {
        psError(PS_ERR_UNKNOWN, false, "Failed to print array");
        psFree(output);
        return false;
    }
    psFree(output);

    return true;
}

static bool addMode(pxConfig *config)
{
    PS_ASSERT_PTR_NON_NULL(config, false);

    // required
    PXOPT_LOOKUP_S64(pub_id, config->args, "-pub_id", true, false);
    PXOPT_LOOKUP_STR(path_base, config->args, "-path_base", true, false);

    // optional
    PXOPT_LOOKUP_STR(hostname, config->args, "-hostname", false, false);
    PXOPT_LOOKUP_F32(dtime_script, config->args, "-dtime_script", false, false);
    PXOPT_LOOKUP_S32(fault, config->args, "-fault", false, false);

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

    if (!publishDoneInsert(config->dbh, pub_id, path_base, hostname, dtime_script, fault)) {
        psError(PS_ERR_UNKNOWN, false, "Unable to add file");
        if (!psDBRollback(config->dbh)) {
            psError(PS_ERR_UNKNOWN, false, "Database error");
        }
        return false;
    }

    if (fault == 0) {
        if (!p_psDBRunQueryF(config->dbh,
                             "UPDATE publishRun SET state = 'full' WHERE pub_id = %" PRId64,
                             pub_id)) {
            psError(PS_ERR_UNKNOWN, false, "Database error");
            if (!psDBRollback(config->dbh)) {
            psError(PS_ERR_UNKNOWN, false, "Database error");
            }
            return false;
        }
    }

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

    return true;
}




static bool revertMode(pxConfig *config)
{
    PS_ASSERT_PTR_NON_NULL(config, false);

    psMetadata *where = psMetadataAlloc(); // WHERE conditions
    PXOPT_COPY_S64(config->args, where, "-pub_id", "publishRun.pub_id", "==");
    PXOPT_COPY_S32(config->args, where, "-fault", "publishDone.fault", "==");
    PXOPT_COPY_STR(config->args, where, "-client_id", "publishClient.client_id", "==");
    PXOPT_COPY_STR(config->args, where, "-comment", "publishClient.comment", "LIKE");
    PXOPT_COPY_STR(config->args, where, "-label", "publishRun.label", "==");

    psString query = pxDataGet("pubtool_revert.sql");
    if (!query) {
        psError(PXTOOLS_ERR_DATA, false, "Failed to retreive SQL statement");
        psFree(where);
        return false;
    }

    if (psListLength(where->list)) {
        psString whereClause = psDBGenerateWhereConditionSQL(where, NULL);
        psStringAppend(&query, " AND %s", whereClause);
        psFree(whereClause);
    }
    psFree(where);

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

    psLogMsg("pubtool", PS_LOG_INFO, "Deleted %" PRIu64 " rows", psDBAffectedRows(config->dbh));

    return true;
}

