// Copyright 2019 Amazon.com, Inc. or its affiliates.
// SPDX-FileCopyrightText: 2024 Redict Contributors
// SPDX-FileCopyrightText: 2024 Salvatore Sanfilippo <antirez at gmail dot com>
//
// SPDX-License-Identifier: BSD-3-Clause

#include "../redictmodule.h"
#include <pthread.h>
#include <unistd.h>

// A simple global user
static RedictModuleUser *global;
static uint64_t global_auth_client_id = 0;

/* HELLOACL.REVOKE
 * Synchronously revoke access from a user. */
int RevokeCommand_RedictCommand(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);

    if (global_auth_client_id) {
        RedictModule_DeauthenticateAndCloseClient(ctx, global_auth_client_id);
        return RedictModule_ReplyWithSimpleString(ctx, "OK");
    } else {
        return RedictModule_ReplyWithError(ctx, "Global user currently not used");
    }
}

/* HELLOACL.RESET
 * Synchronously delete and re-create a module user. */
int ResetCommand_RedictCommand(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);

    RedictModule_FreeModuleUser(global);
    global = RedictModule_CreateModuleUser("global");
    RedictModule_SetModuleUserACL(global, "allcommands");
    RedictModule_SetModuleUserACL(global, "allkeys");
    RedictModule_SetModuleUserACL(global, "on");

    return RedictModule_ReplyWithSimpleString(ctx, "OK");
}

/* Callback handler for user changes, use this to notify a module of
 * changes to users authenticated by the module */
void HelloACL_UserChanged(uint64_t client_id, void *privdata) {
    REDICTMODULE_NOT_USED(privdata);
    REDICTMODULE_NOT_USED(client_id);
    global_auth_client_id = 0;
}

/* HELLOACL.AUTHGLOBAL
 * Synchronously assigns a module user to the current context. */
int AuthGlobalCommand_RedictCommand(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);

    if (global_auth_client_id) {
        return RedictModule_ReplyWithError(ctx, "Global user currently used");
    }

    RedictModule_AuthenticateClientWithUser(ctx, global, HelloACL_UserChanged, NULL, &global_auth_client_id);

    return RedictModule_ReplyWithSimpleString(ctx, "OK");
}

#define TIMEOUT_TIME 1000

/* Reply callback for auth command HELLOACL.AUTHASYNC */
int HelloACL_Reply(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);
    size_t length;

    RedictModuleString *user_string = RedictModule_GetBlockedClientPrivateData(ctx);
    const char *name = RedictModule_StringPtrLen(user_string, &length);

    if (RedictModule_AuthenticateClientWithACLUser(ctx, name, length, NULL, NULL, NULL) ==
            REDICTMODULE_ERR) {
        return RedictModule_ReplyWithError(ctx, "Invalid Username or password");
    }
    return RedictModule_ReplyWithSimpleString(ctx, "OK");
}

/* Timeout callback for auth command HELLOACL.AUTHASYNC */
int HelloACL_Timeout(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);
    return RedictModule_ReplyWithSimpleString(ctx, "Request timedout");
}

/* Private data frees data for HELLOACL.AUTHASYNC command. */
void HelloACL_FreeData(RedictModuleCtx *ctx, void *privdata) {
    REDICTMODULE_NOT_USED(ctx);
    RedictModule_FreeString(NULL, privdata);
}

/* Background authentication can happen here. */
void *HelloACL_ThreadMain(void *args) {
    void **targs = args;
    RedictModuleBlockedClient *bc = targs[0];
    RedictModuleString *user = targs[1];
    RedictModule_Free(targs);

    RedictModule_UnblockClient(bc,user);
    return NULL;
}

/* HELLOACL.AUTHASYNC
 * Asynchronously assigns an ACL user to the current context. */
int AuthAsyncCommand_RedictCommand(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    if (argc != 2) return RedictModule_WrongArity(ctx);

    pthread_t tid;
    RedictModuleBlockedClient *bc = RedictModule_BlockClient(ctx, HelloACL_Reply, HelloACL_Timeout, HelloACL_FreeData, TIMEOUT_TIME);


    void **targs = RedictModule_Alloc(sizeof(void*)*2);
    targs[0] = bc;
    targs[1] = RedictModule_CreateStringFromString(NULL, argv[1]);

    if (pthread_create(&tid, NULL, HelloACL_ThreadMain, targs) != 0) {
        RedictModule_AbortBlock(bc);
        return RedictModule_ReplyWithError(ctx, "-ERR Can't start thread");
    }

    return REDICTMODULE_OK;
}

/* This function must be present on each Redict module. It is used in order to
 * register the commands into the Redict server. */
int RedictModule_OnLoad(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);

    if (RedictModule_Init(ctx,"helloacl",1,REDICTMODULE_APIVER_1)
        == REDICTMODULE_ERR) return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"helloacl.reset",
        ResetCommand_RedictCommand,"",0,0,0) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"helloacl.revoke",
        RevokeCommand_RedictCommand,"",0,0,0) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"helloacl.authglobal",
        AuthGlobalCommand_RedictCommand,"no-auth",0,0,0) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"helloacl.authasync",
        AuthAsyncCommand_RedictCommand,"no-auth",0,0,0) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    global = RedictModule_CreateModuleUser("global");
    RedictModule_SetModuleUserACL(global, "allcommands");
    RedictModule_SetModuleUserACL(global, "allkeys");
    RedictModule_SetModuleUserACL(global, "on");

    global_auth_client_id = 0;

    return REDICTMODULE_OK;
}
