/* $Id: filesystem.c,v 1.3 1998/12/12 20:37:11 jfontain Exp $ */

/* to create the loadable library, use: cc -shared -o libfilesystem.so.1.0 -O2 -fPIC -Wall filesystem.c */
/* pkgIndex.tcl: package ifneeded filesystem 1.0 "load [file join $dir libfilesystem.so.1.0]" */

#include <tcl.h>
#include <sys/vfs.h>
#include <errno.h>
#include <string.h>

static int fileSystemStatistics(ClientData clientData, Tcl_Interp *interpreter, int numberOfArguments, Tcl_Obj * CONST arguments[])
{
    struct statfs statistics;
    Tcl_Obj *object;

    if(numberOfArguments != 2){
        Tcl_WrongNumArgs(interpreter, 1, arguments, "device");
        return TCL_ERROR;
    }
    if(statfs(Tcl_GetStringFromObj(arguments[1], 0), &statistics)<0){
        Tcl_SetObjResult(interpreter, Tcl_NewStringObj(strerror(errno), -1));                /* core takes care of freeing object */
        return TCL_ERROR;
    }
    object = Tcl_NewObj();
    Tcl_ListObjAppendElement(interpreter, object, Tcl_NewLongObj(statistics.f_bsize));             /* optimal transfer block size */
    Tcl_ListObjAppendElement(interpreter, object, Tcl_NewLongObj(statistics.f_blocks));                      /* total data blocks */
    Tcl_ListObjAppendElement(interpreter, object, Tcl_NewLongObj(statistics.f_bavail));  /* free blocks available to normal users */
    Tcl_ListObjAppendElement(interpreter, object, Tcl_NewLongObj(statistics.f_blocks - statistics.f_bfree));       /* used blocks */
    Tcl_SetObjResult(interpreter, object);                                                   /* core takes care of freeing object */
    return TCL_OK;
}

int Filesystem_Init(Tcl_Interp *interpreter)                                       /* create all commands in filesystem namespace */
{
    Tcl_CreateObjCommand(interpreter, "::filesystem::statistics", fileSystemStatistics, 0, 0);
    return Tcl_PkgProvide(interpreter, "filesystem", "1.0");
}

int Filesystem_SafeInit(Tcl_Interp *interpreter)
{
    return Filesystem_Init(interpreter);                                                                 /* all commands are safe */
}
