/*
 * tenkana, a spider that jumps from the checkpoints of your TeX document.
 * Copyright © 2026 निरंजन (Niranjan)
 *
 * tenkana 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, either version 3 of the License, or (at your
 * option) any later version.
 *
 * tenkana 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 tenkana.  If not, see <https://www.gnu.org/licenses/>.
 *
 * tenkana was written by Claude, a large language model (LLM) made by
 * Anthropic.  Its maintainer designs tenkana and tests what it does, but does
 * not understand its code; as far as he knows, no human has reviewed it.
 * Courts are divided on whether material generated by an LLM can be protected
 * by copyright.  Should it be found that the copyright claimant cannot hold
 * copyright in any part of tenkana, that part is in the public domain.
 * Wherever copyright does hold, tenkana is distributed under the terms of the
 * GNU General Public License, version 3 or (at your option) any later version,
 * as stated above.
 */

/*
 * tenkanawatch -- run the TeX compilations of another program through
 * tenkana.
 *
 * `tenkana latexmk thesis' runs latexmk with LD_PRELOAD=libtenkanawatch.so.
 * The library replaces the exec functions (and posix_spawn) in latexmk and
 * in everything it starts: when the program to run is a TeX engine (its
 * file, symlinks followed, is pdftex, luatex, luahbtex, luajittex,
 * luajithbtex or xetex), the call runs
 *
 *     $TENKANA_SELF --inner -- <the same command line>
 *
 * instead, with this library taken out of LD_PRELOAD.  Everything else runs
 * as it would.  texlua and texluac (LuaTeX under another name) are not TeX
 * compilations, and neither is a call whose argv[0] names another program
 * than the file it runs.  $TENKANA_SELF holds the words of tenkana's own
 * command, separated by \037.
 */

#define _GNU_SOURCE
#include <dlfcn.h>

/* tenkana carries this library ready-made, so it must load with any glibc
   since 2.17, not only the one it was built with: glibc 2.34 moved dlsym and
   dladdr into libc under a new version, so ask for the old one. */
#if defined(__GLIBC__) && defined(__x86_64__)
__asm__(".symver dlsym,dlsym@GLIBC_2.2.5");
__asm__(".symver dladdr,dladdr@GLIBC_2.2.5");
#elif defined(__GLIBC__) && defined(__aarch64__)
__asm__(".symver dlsym,dlsym@GLIBC_2.17");
__asm__(".symver dladdr,dladdr@GLIBC_2.17");
#endif
#include <errno.h>
#include <limits.h>
#include <spawn.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

extern char **environ;

static const char *const ENGINES[] = {
    "pdftex", "luatex", "luahbtex", "luajittex", "luajithbtex", "xetex", NULL,
};

static const char *base(const char *p)
{
    const char *s = strrchr(p, '/');
    return s ? s + 1 : p;
}

/* this library's own path, to take it out of LD_PRELOAD */
static char self_lib[PATH_MAX];

__attribute__((constructor)) static void init(void)
{
    Dl_info info;
    if (dladdr((void *)init, &info) && info.dli_fname)
        strncpy(self_lib, info.dli_fname, sizeof self_lib - 1);
}

static int is_engine(const char *path)
{
    char real[PATH_MAX];
    if (!realpath(path, real))
        return 0;
    for (int i = 0; ENGINES[i]; i++)
        if (strcmp(base(real), ENGINES[i]) == 0)
            return 1;
    return 0;
}

/* `file' as execvp finds it, in buf; NULL if not found */
static const char *search(const char *file, char *buf)
{
    if (strchr(file, '/'))
        return file;
    const char *path = getenv("PATH");
    if (!path)
        path = "/bin:/usr/bin";
    size_t flen = strlen(file);
    while (*path) {
        const char *end = strchrnul(path, ':');
        size_t dlen = end - path;
        if (dlen == 0) {  /* an empty entry is the current folder */
            if (flen + 1 <= PATH_MAX) {
                memcpy(buf, file, flen + 1);
                if (access(buf, X_OK) == 0)
                    return buf;
            }
        } else if (dlen + 1 + flen + 1 <= PATH_MAX) {
            memcpy(buf, path, dlen);
            buf[dlen] = '/';
            memcpy(buf + dlen + 1, file, flen + 1);
            if (access(buf, X_OK) == 0)
                return buf;
        }
        path = *end ? end + 1 : end;
    }
    return NULL;
}

/* envp with this library taken out of LD_PRELOAD */
static char **without_self(char *const envp[])
{
    size_t n = 0;
    while (envp[n])
        n++;
    char **out = malloc((n + 1) * sizeof *out);
    if (!out)
        return NULL;
    size_t j = 0;
    for (size_t i = 0; i < n; i++) {
        if (strncmp(envp[i], "LD_PRELOAD=", 11) != 0 || !*self_lib) {
            out[j++] = envp[i];
            continue;
        }
        const char *v = envp[i] + 11;
        char *e = malloc(strlen(envp[i]) + 1);
        if (!e) {
            free(out);
            return NULL;
        }
        strcpy(e, "LD_PRELOAD=");
        char *w = e + 11;
        while (*v) {  /* entries are separated by colons or spaces */
            size_t len = strcspn(v, ": ");
            if (len && !(len == strlen(self_lib) &&
                         strncmp(v, self_lib, len) == 0)) {
                if (w > e + 11)
                    *w++ = ':';
                memcpy(w, v, len);
                w += len;
            }
            v += len;
            if (*v)
                v++;
        }
        *w = 0;
        if (w > e + 11)
            out[j++] = e;
        else
            free(e);
    }
    out[j] = NULL;
    return out;
}

/*
 * If running `path' with `argv' is a TeX compilation, set *npath, *nargv
 * and *nenvp to the tenkana command that runs it, and return 1.
 */
static int redirect(const char *path, char *const argv[], char *const envp[],
                    const char **npath, char ***nargv, char ***nenvp)
{
    const char *self = getenv("TENKANA_SELF");
    if (!self || !*self || !path || !argv || !argv[0])
        return 0;
    if (!is_engine(path))
        return 0;
    const char *a0 = base(argv[0]);
    if (strcmp(a0, "texlua") == 0 || strcmp(a0, "texluac") == 0)
        return 0;
    if (strcmp(a0, base(path)) != 0)
        return 0;
    char *words = strdup(self);
    if (!words)
        return 0;
    size_t nw = 1, na = 0;
    for (char *c = words; *c; c++)
        nw += *c == '\037';
    while (argv[na])
        na++;
    char **v = malloc((nw + 2 + na + 1) * sizeof *v);
    char **e = without_self(envp ? envp : environ);
    if (!v || !e) {
        free(words);
        free(v);
        free(e);
        return 0;
    }
    size_t k = 0;
    for (char *w = words, *c; w; w = c) {
        c = strchr(w, '\037');
        if (c)
            *c++ = 0;
        v[k++] = w;
    }
    v[k++] = "--inner";
    v[k++] = "--";
    /* the command as the program named it, or its file if given by path */
    v[k++] = strchr(argv[0], '/') ? (char *)path : argv[0];
    for (size_t i = 1; i < na; i++)
        v[k++] = argv[i];
    v[k] = NULL;
    *npath = v[0];
    *nargv = v;
    *nenvp = e;
    return 1;
}

#define REAL(name) \
    static __typeof__(name) *real_##name; \
    if (!real_##name) \
        real_##name = (__typeof__(name) *)dlsym(RTLD_NEXT, #name)

int execve(const char *path, char *const argv[], char *const envp[])
{
    REAL(execve);
    const char *np;
    char **nv, **ne;
    if (redirect(path, argv, envp, &np, &nv, &ne))
        return real_execve(np, nv, ne);
    return real_execve(path, argv, envp);
}

int execv(const char *path, char *const argv[])
{
    return execve(path, argv, environ);
}

int execvpe(const char *file, char *const argv[], char *const envp[])
{
    REAL(execvpe);
    char buf[PATH_MAX];
    const char *path = *file ? search(file, buf) : NULL;
    const char *np;
    char **nv, **ne;
    if (path && redirect(path, argv, envp, &np, &nv, &ne))
        return execve(np, nv, ne);
    return real_execvpe(file, argv, envp);
}

int execvp(const char *file, char *const argv[])
{
    return execvpe(file, argv, environ);
}

/* execl, execlp, execle: the arguments as an array */
#define ARGS(first, ap, argv, extra)                        \
    size_t n_ = 1;                                          \
    va_start(ap, first);                                    \
    while (va_arg(ap, char *))                              \
        n_++;                                               \
    va_end(ap);                                             \
    char *argv[n_ + 1];                                     \
    va_start(ap, first);                                    \
    argv[0] = (char *)first;                                \
    for (size_t i_ = 1; i_ <= n_; i_++)                     \
        argv[i_] = va_arg(ap, char *);                      \
    extra;                                                  \
    va_end(ap)

int execl(const char *path, const char *arg, ...)
{
    va_list ap;
    ARGS(arg, ap, argv, (void)0);
    return execve(path, argv, environ);
}

int execlp(const char *file, const char *arg, ...)
{
    va_list ap;
    ARGS(arg, ap, argv, (void)0);
    return execvpe(file, argv, environ);
}

int execle(const char *path, const char *arg, ...)
{
    va_list ap;
    char **envp;
    ARGS(arg, ap, argv, envp = va_arg(ap, char **));
    return execve(path, argv, envp);
}

int posix_spawn(pid_t *pid, const char *path,
                const posix_spawn_file_actions_t *fa,
                const posix_spawnattr_t *attr, char *const argv[],
                char *const envp[])
{
    REAL(posix_spawn);
    const char *np;
    char **nv, **ne;
    if (redirect(path, argv, envp, &np, &nv, &ne)) {
        int r = real_posix_spawn(pid, np, fa, attr, nv, ne);
        free(nv[0]);
        free(nv);
        free(ne);  /* the edited LD_PRELOAD entry is left: it is small */
        return r;
    }
    return real_posix_spawn(pid, path, fa, attr, argv, envp);
}

int posix_spawnp(pid_t *pid, const char *file,
                 const posix_spawn_file_actions_t *fa,
                 const posix_spawnattr_t *attr, char *const argv[],
                 char *const envp[])
{
    REAL(posix_spawnp);
    char buf[PATH_MAX];
    const char *path = *file ? search(file, buf) : NULL;
    if (path && is_engine(path))
        return posix_spawn(pid, path, fa, attr, argv, envp);
    return real_posix_spawnp(pid, file, fa, attr, argv, envp);
}
