#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>

int main(int argc, char **argv) {
    const char *appdir = "/root/linuxdeploy-root";
    char apprun[256], ldbin[256], new_path[4096], new_ldpath[4096];
    struct stat st;

    snprintf(apprun, sizeof(apprun), "%s/AppRun", appdir);
    snprintf(ldbin, sizeof(ldbin), "%s/usr/bin/linuxdeploy", appdir);

    /* Strip --appimage-extract-and-run: AppImage runtime flag, not a linuxdeploy flag */
    char **new_argv = malloc((argc + 1) * sizeof(char *));
    int new_argc = 0;
    new_argv[new_argc++] = argv[0];
    for (int i = 1; i < argc; i++) {
        if (strcmp(argv[i], "--appimage-extract-and-run") != 0)
            new_argv[new_argc++] = argv[i];
    }
    new_argv[new_argc] = NULL;

    setenv("APPDIR", appdir, 1);

    char *old_path = getenv("PATH");
    snprintf(new_path, sizeof(new_path), "%s/usr/bin:%s", appdir, old_path ? old_path : "");
    setenv("PATH", new_path, 1);

    char *old_ldpath = getenv("LD_LIBRARY_PATH");
    snprintf(new_ldpath, sizeof(new_ldpath), "%s/usr/lib:%s/usr/lib/x86_64-linux-gnu:%s",
             appdir, appdir, old_ldpath ? old_ldpath : "");
    setenv("LD_LIBRARY_PATH", new_ldpath, 1);

    /* Write diagnostic log visible in the always() post-step */
    FILE *log = fopen("/tmp/ld-wrapper.log", "w");
    if (log) {
        fprintf(log, "APPDIR=%s\n", appdir);
        fprintf(log, "AppRun exists: %s\n", stat(apprun, &st) == 0 ? "yes" : "NO");
        fprintf(log, "linuxdeploy exists: %s\n", stat(ldbin, &st) == 0 ? "yes" : "NO");
        fprintf(log, "argc=%d new_argc=%d\n", argc, new_argc);
        fprintf(log, "args:");
        for (int i = 0; i < new_argc; i++) fprintf(log, " [%s]", new_argv[i]);
        fprintf(log, "\nPATH=%s\n", getenv("PATH") ? getenv("PATH") : "(null)");
        fclose(log);
    }

    if (stat(ldbin, &st) == 0)
        execv(ldbin, new_argv);
    execv(apprun, new_argv);
    return 1;
}
