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

static const char *private_dirs[] = {
    "/data/data/bin.mt.plus/files",
    "/data/data/bin.mt.manager/files",
    "/data/data/bin.mt.plus.test/files",
    "/data/data/com.termux/files/home",
    NULL
};

static const char* find_private_dir(void) {
    for (int i = 0; private_dirs[i]; i++) {
        if (access(private_dirs[i], F_OK) == 0) {
            return private_dirs[i];
        }
    }
    return NULL;
}

int runner_exec(const char *path) {
    const char *dir = find_private_dir();
    if (!dir) {
        fprintf(stderr, "错误: 未找到私有目录 (MT/Termux)\n");
        return 1;
    }

    char temp_path[512];
    const char *name = strrchr(path, '/');
    name = name ? name + 1 : path;
    snprintf(temp_path, sizeof(temp_path), "%s/temp_%s", dir, name);

    FILE *src = fopen(path, "rb");
    if (!src) {
        fprintf(stderr, "错误: 无法读取 %s\n", path);
        return 1;
    }

    FILE *dst = fopen(temp_path, "wb");
    if (!dst) {
        fclose(src);
        fprintf(stderr, "错误: 无法写入 %s\n", temp_path);
        return 1;
    }

    unsigned char buf[4096];
    int n;
    while ((n = fread(buf, 1, sizeof(buf), src)) > 0) {
        fwrite(buf, 1, n, dst);
    }

    fclose(src);
    fclose(dst);

    chmod(temp_path, 0755);

    pid_t pid = fork();
    if (pid == 0) {
        execl(temp_path, temp_path, NULL);
        perror("execl");
        exit(1);
    } else {
        int status;
        waitpid(pid, &status, 0);
        unlink(temp_path);
        return WIFEXITED(status) ? WEXITSTATUS(status) : 1;
    }
}