#include "Python.h"

#include <fcntl.h>
//#include <errno.h>
#include <unistd.h>
#include <sys/param.h>

static PyObject* get_canonical_case(PyObject *self, PyObject *args)
{
    char *path;
    char canonical_path[sizeof(char)*MAXPATHLEN+1];
    
    int fd;

    // Python seems to return the correct error here.
    // If you explicitly free path, it crashes.
    if (!PyArg_ParseTuple(args, "s", &path))
        return NULL;
    
    fd = open(path, O_RDONLY);

    // both open and fcntl will set errno if fine grained error reporting is desired.
    // currently there is no specific error report.
    if(fd == -1 || fcntl(fd, F_GETPATH, canonical_path) == -1){
        PyErr_SetString(PyExc_IOError, "Unable to open file"); 
        return NULL;
    }
    
    // close the file
    if(close(fd) == -1){
        PyErr_SetString(PyExc_IOError, "Failed to close file");
        return NULL;
    }
    return Py_BuildValue("s", canonical_path);
}

static PyMethodDef FilecaseMethods[] = {
    {"get_canonical_case",  get_canonical_case, METH_VARARGS,
        "Get the canonical case of the file."},
    {NULL, NULL, 0, NULL}        /* Sentinel */
};

PyMODINIT_FUNC initfilecase(void)
{
    (void) Py_InitModule("filecase", FilecaseMethods);
}

