/*
   vdev: a virtual device manager for *nix
   Copyright (C) 2023  Aitor C.Z.

   This program is dual-licensed: you can redistribute it and/or modify
   it under the terms of the GNU General Public License version 3 or later as 
   published by the Free Software Foundation. For the terms of this 
   license, see LICENSE.GPLv3+ or <http://www.gnu.org/licenses/>.

   You are free to use this program under the terms of the GNU General
   Public License, 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.

   Alternatively, you are free to use this program under the terms of the 
   Internet Software Consortium License, but WITHOUT ANY WARRANTY; without
   even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
   For the terms of this license, see LICENSE.ISC or 
   <http://www.isc.org/downloads/software-support-policy/isc-license/>.
*/

#include "misc.h"
#include "dmi_chassis_builtin.h"
#include "sbuf.h"
#include "sglib.h"

SGLIB_DEFINE_VECTOR_FUNCTIONS(cstr);

#include <pstat/libpstat.h>

// Usage: strncpy_t(str1, sizeof(str1), str2, strlen(str2));
// Copy string "in" with at most "insz" chars to buffer "out", which
// is "outsz" bytes long. The output is always 0-terminated. Unlike
// strncpy(), strncpy_t() does not zero fill remaining space in the
// output buffer:
char *strncpy_t(char *out, size_t outsz, const char *in, size_t insz)
{
    /* Real-time protection (don't use assert) */
    if (out == NULL || outsz == 0)
        return out;

    char *saved_out = out;

    /* copy, always leaving space for the final \0 */
    while (outsz > 1 && insz > 0 && in && *in) {
        *out++ = *in++;
        outsz--;
        insz--;
    }

    /* Ensure sentinel */
    *out = '\0';

    return saved_out;
}

bool vdev_fanotify_path_is_login_or_xorg(const char *exe_path)
{
    const char *slash;
    const char *base;

    if (exe_path == NULL || exe_path[0] == '\0')
        return false;
    if (strcmp(exe_path, "/usr/bin/Xorg") == 0)
        return true;
    slash = strrchr(exe_path, '/');
    base = slash ? slash + 1 : exe_path;
    return strcmp(base, "login") == 0;
}

bool vdev_dmi_chassis_type_is_tower_or_desktop(void)
{
    char line[1024];
    const char *env = getenv(VDEV_DMI_CHASSIS_BUILTIN_ENV);
    const char *builtin_cmd =
        (env != NULL && env[0] != '\0') ? env : VDEV_DMI_CHASSIS_BUILTIN_DEFAULT;
    static const char pipeline[] =
        "/usr/sbin/dmidecode -t chassis | /bin/grep Type | /usr/bin/cut -d' ' -f2";
    const char *cmds[2] = { builtin_cmd, pipeline };
    unsigned i;

    for (i = 0; i < 2; i++) {
        FILE *fp = popen(cmds[i], "r");

        if (fp == NULL)
            continue;
        if (fgets(line, sizeof line, fp)) {
            line[strcspn(line, "\n")] = '\0';
            pclose(fp);
            return !strcmp(line, "Tower") || !strcmp(line, "Desktop");
        }
        pclose(fp);
    }
    return false;
}

// thread-safe and async-safe int to string for base 10
void itoa10_safe(int val, char *str)
{
    int i = 0;
    int len = 0;
    int j = 0;
    bool neg = false;
   
    /* sign check */
    if (val < 0) {
        val = -val;
        neg = true;
    }
   
    /* consume, lowest-order to highest-order */
    if (val == 0) {
        str[i] = '0';
        i++;
    } else {
        while (val > 0) {
            int r = val % 10;
            str[i] = '0' + r;
            i++;
            val /= 10;
        }
    }
   
    if (neg) {
        str[i] = '-';
        i++;
    }
   
    len = i;
    i--;
   
    /* reverse order to get the number */
    while (j < i) {
        char tmp = *(str + i);
        *(str + i) = *(str + j);
        *(str + j) = tmp;
        j++;
        i--;
    }
   
    str[len] = '\0';
}

void vdev_detach_session(void)
{
    pid_t pid;
    long maxfd;
    int fd;

    pid = fork();
    if (pid < 0)
        exit(EXIT_FAILURE);
    if (pid > 0)
        exit(EXIT_SUCCESS);

    if (setsid() < 0)
        exit(EXIT_FAILURE);

    /* Avoid accumulating zombies for reparented short-lived children. */
    signal(SIGCHLD, SIG_IGN);

    pid = fork();
    if (pid < 0)
        exit(EXIT_FAILURE);
    if (pid > 0)
        exit(EXIT_SUCCESS);

    umask(0);
    if (chdir("/tmp") != 0)
        exit(EXIT_FAILURE);

    /* Drop inherited fds (bounded: _SC_OPEN_MAX can be huge on Linux). */
    maxfd = sysconf(_SC_OPEN_MAX);
    if (maxfd < 0)
        maxfd = 256;
    else if (maxfd > 4096)
        maxfd = 4096;
    for (fd = (int)maxfd - 1; fd >= 0; fd--)
        (void)close(fd);

    fd = open("/dev/null", O_RDWR);
    if (fd != -1) {
        dup2(fd, STDIN_FILENO);
        dup2(fd, STDOUT_FILENO);
        dup2(fd, STDERR_FILENO);
        if (fd > 2)
            close(fd);
    }
}

int vdev_cstr_vector_free_all(struct sglib_cstr_vector *vec)
{
    if (!vec)
        return 0;

    for (size_t i = 0; i < sglib_cstr_vector_size(vec); i++) {
        char *ptr = sglib_cstr_vector_at(vec, i);

        if (ptr) {
            free(ptr);
            sglib_cstr_vector_set(vec, NULL, i);
        }
    }

    return 0;
}
