#!/usr/bin/env python

import fuse
import os, sys
import errno
import time
import stat
import datetime


fuse.fuse_python_api = (0, 2)


def dir_attributes(number_of_entries = 2):
    res = fuse.Stat()
    res.st_mode = stat.S_IFDIR | 0555
    res.st_nlink = number_of_entries
    res.st_atime = 2 ** 30
    res.st_mtime = 2 ** 30
    res.st_ctime = 2 ** 30
    return res

def file_attributes(number_of_bytes = 0):
    res = fuse.Stat()
    res.st_mode = stat.S_IFREG | 0444
    res.st_nlink = 1
    res.st_size = number_of_bytes
    res.st_atime = 2 ** 30
    res.st_mtime = 2 ** 30
    res.st_ctime = 2 ** 30
    return res

FILES = {
    'hello' : 'world\n',
    'large' : 'A' * (2 ** 20)
}

class Memory(fuse.Fuse):
    def __init__(self):
        fuse.Fuse.__init__(self)

    def getattr(self, path, fh=None):
        if path == '/':
            return dir_attributes(len(FILES) + 2)
        elif path and path[1:] in FILES:
            return file_attributes(len(FILES[path[1:]]))
        return -errno.ENOENT;

    def readdir(self, path, fh):
        if path == '/':
            return [fuse.Direntry(e) for e in ['.', '..'] + FILES.keys()]
        return -errno.ENOENT;

    def read(self, path, length, offset):
        data = FILES[path[1:]]
        # extract data from offset
        data = data[offset:][:length]
        # for demostration, return only chunks up to 1024 bytes
        return data[:1024]

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print 'usage: %s <mountpoint> [-f]' % sys.argv[0]
        print '       %s -h' % sys.argv[0]
        exit(1)
    fs = Memory()
    fs.parse(values=fs, errex=1)
    fs.main()

