/*
 * Copyright (c) Cloud Linux GmbH & Cloud Linux Software, Inc 2010-2018 All Rights Reserved
 *
 * Licensed under CLOUD LINUX LICENSE AGREEMENT
 * http://cloudlinux.com/docs/LICENSE.TXT
 *
 */

#include <lscapi_util.h>
#include <unistd.h>

#ifndef WITHOUT_SENTRY

#ifndef LSAPI_SENTRY_PY
#define LSAPI_SENTRY_PY "/usr/share/lve/modlscapi/utils/lsapi_sentry.py"
#endif

static int lsapi_sentry = 0;

static const char* args[] =
{
    "/opt/cloudlinux/venv/bin/python3",
    LSAPI_SENTRY_PY,
    NULL,
    NULL
};

static const char* envs[] =
{
    "PATH=/bin:/usr/bin:/usr/local/bin",
    NULL,
    NULL,
    NULL
};

void set_lsapi_sentry(int value)
{
    lsapi_sentry = value;
}

int get_lsapi_sentry(void)
{
    return lsapi_sentry;
}

#if __GNUC__ >= 7
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-variable"
#endif
void lscapi_process_sentry_log(void)
{
    if (get_lsapi_sentry() == 0)
        return;

    if (access(LSAPI_SENTRY_PY, F_OK) == -1) {
        set_lsapi_sentry(0);
        return;
    }

    pid_t pid = lscapi_proc_create(args, envs);
//    if (pid == -1)
//        fprintf(stderr, "Spawn process for lsapi sentry failed\n");
}
#if __GNUC__ >= 7
#pragma GCC diagnostic pop
#endif

static void write_to_log(int fd, const char *str, unsigned int size)
{
    ssize_t ret;
    unsigned int written = 0;

    while (written < size) {
        do {
            ret = write(fd, str + written, size - written);
        } while (ret == -1 && errno == EINTR);

        if (ret == -1) {
            break;
        } else {
            written += ret;
        }
    }
}

void lscapi_sentry_log(int level, const char *fmt, const char *buf)
{
    char fname[] = "/var/log/mod_lsapi/messages";
    unsigned int size = -1;
    int fd = -1;

    if (level == APLOG_NOTICE || get_lsapi_sentry() == 0)
       return;

    size = strlen(buf);

    fd = open(fname, O_WRONLY | O_APPEND | O_CREAT, 0644);
    if (fd == -1) {
        //int e = errno;
        //fprintf(stderr, "Open file: %s for lsapi logging failed. Error: %s\n",
        //        fname, strerror(e));
        set_lsapi_sentry(0);
        return;
    }

    write_to_log(fd, "\n", 1);
    write_to_log(fd, fmt, strlen(fmt));
    write_to_log(fd, "\001", 1);
    write_to_log(fd, buf, size);

    close(fd);
}

#endif //WITHOUT_SENTRY
