#!/usr/bin/python

import os
import subprocess
from pyinotify import *

local_path = sys.argv[1]  # cartella da monitorare
local_dir = sys.argv[2]   # elenco sub-directories da monitorare separate da ","
db_folder = sys.argv[3]   # cartella di destinazione su dropbox

events = IN_CLOSE_WRITE | IN_MOVED_TO

class PTmp(ProcessEvent):
   def process_IN_CLOSE_WRITE(self, event):
      self.processa_evento(event)
   def process_IN_MOVED_TO(self, event):
      self.processa_evento(event)
   def processa_evento(self, event):
      #print "Process: %s" % os.path.join(event.path, event.name)
      lpath=local_path.split('/')
      epath=event.path.split('/')
      # costruzione percorso cartelle su dropbox (se esistono e' tempo perso)
      newpath=db_folder[:]
      for ind_dir in range(len(lpath), len(epath)):
         #print epath[ind_dir]
         newpath=os.path.join(newpath, epath[ind_dir])
         # si e visto che la funzione upload generare l'albero di detsinazione se serve
         # subprocess.call('/root/dropbox_uploader.sh mkdir %s' % (newpath), shell=True)      
      # carica file su dropbox
      subprocess.call('/root/dropbox_uploader.sh upload %s %s' % (os.path.join(event.path, event.name), os.path.join(newpath, event.name)), shell=True)

wm = WatchManager()
notifier = Notifier(wm, PTmp())
subdirs = local_dir.split(",")
for subdir in subdirs:
   wm.add_watch(os.path.join(local_path, subdir), events, rec=True, auto_add=True)

while True:  # loop forever
   try:
      # process the queue of events as explained above
      notifier.process_events()
      if notifier.check_events():
         # read notified events and enqeue them
         notifier.read_events()
         # you can do some tasks here...
   except KeyboardInterrupt:
      # destroy the inotify's instance on this interrupt (stop monitoring)
      notifier.stop()
      break
