#include <Python.h>
#include <exim4/local_scan.h>
#include <dlfcn.h>

void* ll(char* filename)
{
    printf("mylib.c::ll()");
    void* handle = dlopen( filename, RTLD_NOW );
    if( !handle )
    {
        printf("error: %s",  dlerror());
        return NULL;
    }

    return handle;
}

static int run_file(char* filename)
{
    printf("mylib.c::run_file");
    FILE* exp_file = fopen(filename, "r");
    return PyRun_SimpleFile(exp_file, filename);
}
/* A static module */

/* 'self' is not used */
static PyObject *
pyexim_load_file(PyObject *self, PyObject* args)
{
    run_file("/usr/lib/python2.6/exim_local_scan2.py");
    return NULL;
}

static PyObject *
pyexim_hello(PyObject *self, PyObject* args)
{
    printf("mylib.c::hello()");
    return PyRun_SimpleString("print(\"Hello\")\n");
}
static PyMethodDef pyexim_methods[] = {
    {"load_file", pyexim_load_file,  METH_NOARGS, "Return the meaning of everything."},
    {"hello", pyexim_hello,  METH_NOARGS, "Return the meaning of everything."},
    {NULL, NULL}       /* sentinel */
};

void
initpyexim(void)
{
    PyImport_AddModule("pyexim");
    Py_InitModule("pyexim", pyexim_methods);
    PyRun_SimpleString("import sys\n");
}

/* Return the verion of the local_scan ABI, if being compiled as a .so */
int local_scan_version_major(void)
{
    return LOCAL_SCAN_ABI_VERSION_MAJOR;
}

int local_scan_version_minor(void)
{
    return LOCAL_SCAN_ABI_VERSION_MINOR;
}


int local_scan(int fd, uschar **return_text)
{
    char* filename = "libpython2.6.so";
    void* handle = dlopen( filename, RTLD_LAZY | RTLD_GLOBAL );

    if( !handle )
    {
        printf("error: %s",  dlerror());
        return LOCAL_SCAN_REJECT;
    }

    if (!Py_IsInitialized()) 
    {
        Py_Initialize();
    }

    initpyexim();

    run_file("/usr/lib/python2.6/exim_local_scan2.py");
    return LOCAL_SCAN_REJECT;
}

int go()
{
    printf("mylib.c::go()");
    local_scan(0, NULL);
    return 0;
}
