#!/usr/bin/python

import os, os.path
import signal
import sys
import tempfile
import shutil

import pyinotify

# These are documented in the man page: "man 7 inotify"
MASK = (
    # pyinotify.IN_ACCESS |
    # pyinotify.IN_ATTRIB |
    # pyinotify.IN_CLOSE_WRITE |
    # pyinotify.IN_CLOSE_NOWRITE |
    pyinotify.IN_CREATE |
    pyinotify.IN_DELETE |
    pyinotify.IN_DELETE_SELF |
    pyinotify.IN_MODIFY |
    pyinotify.IN_MOVE_SELF |
    pyinotify.IN_MOVED_FROM |
    pyinotify.IN_MOVED_TO
    # pyinotify.IN_OPEN
)

class EventHandler(pyinotify.ProcessEvent):
    def process_default(self, event):
        print "Handled: %s for %s" % (event.maskname, event.pathname)

if __name__ == "__main__":
    handler = EventHandler()

    # The watch manager stores the watches and provides operations on watches
    wm = pyinotify.WatchManager()

    temp_dir = tempfile.mkdtemp(prefix='pyin-')

    print "Temp dir: %s" % temp_dir

    wdd = wm.add_watch(temp_dir, MASK, rec=True, auto_add=True)

    notifier = pyinotify.ThreadedNotifier(wm, EventHandler())
    # notifier.daemon = True

    # Remove the temp tree on exit
    def handler(signum, frame):
        print "Interrupted, stopping notifications"
        notifier.stop()
        try:
            shutil.rmtree(temp_dir)
        except OSError:
            pass

        sys.exit(0)

    signal.signal(signal.SIGINT, handler)

    print "Interrupt (Ctrl-C) to exit"

    notifier.start()

    signal.pause()
