// SPDX-FileCopyrightText: 2024 Redict Contributors
// SPDX-FileCopyrightText: 2024 Salvatore Sanfilippo <antirez at gmail dot com>
//
// SPDX-License-Identifier: BSD-3-Clause
// SPDX-License-Identifier: LGPL-3.0-only

#include "redictmodule.h"

#include <string.h>
#include <strings.h>

static RedictModuleString *log_key_name;

static const char log_command_name[] = "commandfilter.log";
static const char ping_command_name[] = "commandfilter.ping";
static const char retained_command_name[] = "commandfilter.retained";
static const char unregister_command_name[] = "commandfilter.unregister";
static const char unfiltered_clientid_name[] = "unfilter_clientid";
static int in_log_command = 0;

unsigned long long unfiltered_clientid = 0;

static RedictModuleCommandFilter *filter, *filter1;
static RedictModuleString *retained;

int CommandFilter_UnregisterCommand(RedictModuleCtx *ctx, RedictModuleString **argv, int argc)
{
    (void) argc;
    (void) argv;

    RedictModule_ReplyWithLongLong(ctx,
            RedictModule_UnregisterCommandFilter(ctx, filter));

    return REDICTMODULE_OK;
}

int CommandFilter_PingCommand(RedictModuleCtx *ctx, RedictModuleString **argv, int argc)
{
    (void) argc;
    (void) argv;

    RedictModuleCallReply *reply = RedictModule_Call(ctx, "ping", "c", "@log");
    if (reply) {
        RedictModule_ReplyWithCallReply(ctx, reply);
        RedictModule_FreeCallReply(reply);
    } else {
        RedictModule_ReplyWithSimpleString(ctx, "Unknown command or invalid arguments");
    }

    return REDICTMODULE_OK;
}

int CommandFilter_Retained(RedictModuleCtx *ctx, RedictModuleString **argv, int argc)
{
    (void) argc;
    (void) argv;

    if (retained) {
        RedictModule_ReplyWithString(ctx, retained);
    } else {
        RedictModule_ReplyWithNull(ctx);
    }

    return REDICTMODULE_OK;
}

int CommandFilter_LogCommand(RedictModuleCtx *ctx, RedictModuleString **argv, int argc)
{
    RedictModuleString *s = RedictModule_CreateString(ctx, "", 0);

    int i;
    for (i = 1; i < argc; i++) {
        size_t arglen;
        const char *arg = RedictModule_StringPtrLen(argv[i], &arglen);

        if (i > 1) RedictModule_StringAppendBuffer(ctx, s, " ", 1);
        RedictModule_StringAppendBuffer(ctx, s, arg, arglen);
    }

    RedictModuleKey *log = RedictModule_OpenKey(ctx, log_key_name, REDICTMODULE_WRITE|REDICTMODULE_READ);
    RedictModule_ListPush(log, REDICTMODULE_LIST_HEAD, s);
    RedictModule_CloseKey(log);
    RedictModule_FreeString(ctx, s);

    in_log_command = 1;

    size_t cmdlen;
    const char *cmdname = RedictModule_StringPtrLen(argv[1], &cmdlen);
    RedictModuleCallReply *reply = RedictModule_Call(ctx, cmdname, "v", &argv[2], argc - 2);
    if (reply) {
        RedictModule_ReplyWithCallReply(ctx, reply);
        RedictModule_FreeCallReply(reply);
    } else {
        RedictModule_ReplyWithSimpleString(ctx, "Unknown command or invalid arguments");
    }

    in_log_command = 0;

    return REDICTMODULE_OK;
}

int CommandFilter_UnfilteredClientId(RedictModuleCtx *ctx, RedictModuleString **argv, int argc)
{
    if (argc < 2)
        return RedictModule_WrongArity(ctx);

    long long id;
    if (RedictModule_StringToLongLong(argv[1], &id) != REDICTMODULE_OK) {
        RedictModule_ReplyWithError(ctx, "invalid client id");
        return REDICTMODULE_OK;
    }
    if (id < 0) {
        RedictModule_ReplyWithError(ctx, "invalid client id");
        return REDICTMODULE_OK;
    }

    unfiltered_clientid = id;
    RedictModule_ReplyWithSimpleString(ctx, "OK");
    return REDICTMODULE_OK;
}

/* Filter to protect against Bug #11894 reappearing
 *
 * ensures that the filter is only run the first time through, and not on reprocessing
 */
void CommandFilter_BlmoveSwap(RedictModuleCommandFilterCtx *filter)
{
    if (RedictModule_CommandFilterArgsCount(filter) != 6)
        return;

    RedictModuleString *arg = RedictModule_CommandFilterArgGet(filter, 0);
    size_t arg_len;
    const char *arg_str = RedictModule_StringPtrLen(arg, &arg_len);

    if (arg_len != 6 || strncmp(arg_str, "blmove", 6))
        return;

    /*
     * Swapping directional args (right/left) from source and destination.
     * need to hold here, can't push into the ArgReplace func, as it will cause other to freed -> use after free
     */
    RedictModuleString *dir1 = RedictModule_HoldString(NULL, RedictModule_CommandFilterArgGet(filter, 3));
    RedictModuleString *dir2 = RedictModule_HoldString(NULL, RedictModule_CommandFilterArgGet(filter, 4));
    RedictModule_CommandFilterArgReplace(filter, 3, dir2);
    RedictModule_CommandFilterArgReplace(filter, 4, dir1);
}

void CommandFilter_CommandFilter(RedictModuleCommandFilterCtx *filter)
{
    unsigned long long id = RedictModule_CommandFilterGetClientId(filter);
    if (id == unfiltered_clientid) return;

    if (in_log_command) return;  /* don't process our own RM_Call() from CommandFilter_LogCommand() */

    /* Fun manipulations:
     * - Remove @delme
     * - Replace @replaceme
     * - Append @insertbefore or @insertafter
     * - Prefix with Log command if @log encountered
     */
    int log = 0;
    int pos = 0;
    while (pos < RedictModule_CommandFilterArgsCount(filter)) {
        const RedictModuleString *arg = RedictModule_CommandFilterArgGet(filter, pos);
        size_t arg_len;
        const char *arg_str = RedictModule_StringPtrLen(arg, &arg_len);

        if (arg_len == 6 && !memcmp(arg_str, "@delme", 6)) {
            RedictModule_CommandFilterArgDelete(filter, pos);
            continue;
        } 
        if (arg_len == 10 && !memcmp(arg_str, "@replaceme", 10)) {
            RedictModule_CommandFilterArgReplace(filter, pos,
                    RedictModule_CreateString(NULL, "--replaced--", 12));
        } else if (arg_len == 13 && !memcmp(arg_str, "@insertbefore", 13)) {
            RedictModule_CommandFilterArgInsert(filter, pos,
                    RedictModule_CreateString(NULL, "--inserted-before--", 19));
            pos++;
        } else if (arg_len == 12 && !memcmp(arg_str, "@insertafter", 12)) {
            RedictModule_CommandFilterArgInsert(filter, pos + 1,
                    RedictModule_CreateString(NULL, "--inserted-after--", 18));
            pos++;
        } else if (arg_len == 7 && !memcmp(arg_str, "@retain", 7)) {
            if (retained) RedictModule_FreeString(NULL, retained);
            retained = RedictModule_CommandFilterArgGet(filter, pos + 1);
            RedictModule_RetainString(NULL, retained);
            pos++;
        } else if (arg_len == 4 && !memcmp(arg_str, "@log", 4)) {
            log = 1;
        }
        pos++;
    }

    if (log) RedictModule_CommandFilterArgInsert(filter, 0,
            RedictModule_CreateString(NULL, log_command_name, sizeof(log_command_name)-1));
}

int RedictModule_OnLoad(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    if (RedictModule_Init(ctx,"commandfilter",1,REDICTMODULE_APIVER_1)
            == REDICTMODULE_ERR) return REDICTMODULE_ERR;

    if (argc != 2 && argc != 3) {
        RedictModule_Log(ctx, "warning", "Log key name not specified");
        return REDICTMODULE_ERR;
    }

    long long noself = 0;
    log_key_name = RedictModule_CreateStringFromString(ctx, argv[0]);
    RedictModule_StringToLongLong(argv[1], &noself);
    retained = NULL;

    if (RedictModule_CreateCommand(ctx,log_command_name,
                CommandFilter_LogCommand,"write deny-oom",1,1,1) == REDICTMODULE_ERR)
            return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,ping_command_name,
                CommandFilter_PingCommand,"deny-oom",1,1,1) == REDICTMODULE_ERR)
            return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,retained_command_name,
                CommandFilter_Retained,"readonly",1,1,1) == REDICTMODULE_ERR)
            return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,unregister_command_name,
                CommandFilter_UnregisterCommand,"write deny-oom",1,1,1) == REDICTMODULE_ERR)
            return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx, unfiltered_clientid_name,
                CommandFilter_UnfilteredClientId, "admin", 1,1,1) == REDICTMODULE_ERR)
            return REDICTMODULE_ERR;

    if ((filter = RedictModule_RegisterCommandFilter(ctx, CommandFilter_CommandFilter, 
                    noself ? REDICTMODULE_CMDFILTER_NOSELF : 0))
            == NULL) return REDICTMODULE_ERR;

    if ((filter1 = RedictModule_RegisterCommandFilter(ctx, CommandFilter_BlmoveSwap, 0)) == NULL)
        return REDICTMODULE_ERR;

    if (argc == 3) {
        const char *ptr = RedictModule_StringPtrLen(argv[2], NULL);
        if (!strcasecmp(ptr, "noload")) {
            /* This is a hint that we return ERR at the last moment of OnLoad. */
            RedictModule_FreeString(ctx, log_key_name);
            if (retained) RedictModule_FreeString(NULL, retained);
            return REDICTMODULE_ERR;
        }
    }

    return REDICTMODULE_OK;
}

int RedictModule_OnUnload(RedictModuleCtx *ctx) {
    RedictModule_FreeString(ctx, log_key_name);
    if (retained) RedictModule_FreeString(NULL, retained);

    return REDICTMODULE_OK;
}
