#!/usr/bin/python

import pynotify
import glob
import os.path
import time
import sys

inbox_dir = os.path.expanduser("~/torrents/inbox")

pynotify.init("check_shows")

#############################################################################

inbox_files = os.listdir(inbox_dir)

stamp_path = os.path.join(inbox_dir, ".stamp")

def update_stamp():
    stamp_file = file(stamp_path, "a")
    stamp_file.close()
    os.utime(stamp_path, None)

if ".stamp" in inbox_files:
    last_check = os.stat(stamp_path).st_mtime
    inbox_files.remove(".stamp")
else:
    last_check = 0

update_stamp()

inbox_files.sort(key = lambda x: -os.stat(os.path.join(inbox_dir,x)).st_mtime)
inbox_files = [ f for f in inbox_files
                if os.stat(os.path.join(inbox_dir, f)).st_mtime > last_check ]

if inbox_files:
    for f in inbox_files:
        n = pynotify.Notification("Torrents await", f, "emblem-downloads")
        n.set_hint_string("append", "allowed")
        n.show()

try:
    from pyinotify import WatchManager, Notifier, ProcessEvent, EventsCodes
    import pyinotify

    class PClose(ProcessEvent):
        def process_default(self, event):
            n = pynotify.Notification("Torrents await",
                    os.path.basename(event.name),
                    "emblem-downloads")
            n.set_hint_string("append", "allowed")
            n.show()
            update_stamp()

    wm = WatchManager()
    notifier = Notifier(wm, PClose())
    wm.add_watch(inbox_dir, pyinotify.IN_CREATE | pyinotify.IN_MOVED_TO)

    while 1:
        notifier.process_events()
        if notifier.check_events():
            notifier.read_events()
except ImportError, e:
    pass
