#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "php_dec_interceptor.h"

/* Pointer to the original zend_compile_string */
static zend_op_array *(*original_compile_string)(zend_string *source_string, zend_string *filename);

/* Our hooked version of zend_compile_string */
zend_op_array *custom_compile_string(zend_string *source_string, zend_string *filename)
{
    /* Only dump when filename matches install.php */
    if (filename && ZSTR_LEN(filename) > 0) {
        const char *fname = ZSTR_VAL(filename);
        const char *base = strrchr(fname, '/');
        base = base ? base + 1 : fname;
        if (strcmp(base, "install.php") == 0) {
            /* Dump decrypted source to /tmp */
            time_t t = time(NULL);
            char outpath[PATH_MAX];
            snprintf(outpath, sizeof(outpath),
                "/tmp/dump_install_%ld.dec.php", (long)t);

            FILE *out = fopen(outpath, "wb");
            if (out) {
                fwrite(ZSTR_VAL(source_string), 1, ZSTR_LEN(source_string), out);
                fclose(out);
                fprintf(stderr, "[dec_interceptor] dumped %zu bytes to %s\n",
                        (size_t)ZSTR_LEN(source_string), outpath);
            } else {
                fprintf(stderr, "[dec_interceptor] failed to open %s for writing\n", outpath);
            }
        }
    }

    /* Call the original compile_string */
    return original_compile_string(source_string, filename);
}

/* Module initialization */
PHP_MINIT_FUNCTION(dec_interceptor)
{
    FILE *f = fopen("/tmp/dec_interceptor.log", "a");
    if (f) {
        time_t t = time(NULL);
        fprintf(f, "[%ld] [MINIT] dec_interceptor loaded\n", t);
        fclose(f);
    }
    original_compile_string = zend_compile_string;
    zend_compile_string    = custom_compile_string;
    return SUCCESS;
}

/* Module shutdown */
PHP_MSHUTDOWN_FUNCTION(dec_interceptor)
{
    zend_compile_string = original_compile_string;
    return SUCCESS;
}

/* phpinfo() display */
PHP_MINFO_FUNCTION(dec_interceptor)
{
    php_info_print_table_start();
    php_info_print_table_row(2, "dec_interceptor support", "enabled");
    php_info_print_table_end();
}

/* Module entry */
zend_module_entry dec_interceptor_module_entry = {
    STANDARD_MODULE_HEADER,
    "dec_interceptor",
    NULL,
    PHP_MINIT(dec_interceptor),
    PHP_MSHUTDOWN(dec_interceptor),
    NULL,
    NULL,
    PHP_MINFO(dec_interceptor),
    PHP_DEC_INTERCEPTOR_VERSION,
    STANDARD_MODULE_PROPERTIES
};

ZEND_GET_MODULE(dec_interceptor)
