#!/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 ","
own_folder = sys.argv[3]    # cartella di destinazione su owncloud
own_user = sys.argv[4]      # utente di owncloud

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 owncloud (se esistono e' tempo perso)
      newpath=own_folder[:]
      for ind_dir in range(len(lpath), len(epath)):
         print epath[ind_dir]
         subprocess.call('owncmd mkdir %s %s %s > /dev/null' % (epath[ind_dir], newpath, own_user), shell=True)
         newpath=os.path.join(newpath, epath[ind_dir])
      # cancella vecchia copia del file su owncloud (se non esiste e' tempo perso) per evitare che sia stranamente rinominata la nuova copia
      subprocess.call('owncmd delfile %s %s %s > /dev/null' % (event.name, newpath, own_user), shell=True)
      # carica file su owncloud
      subprocess.call('owncmd upload %s %s %s > /dev/null' % (newpath, os.path.join(event.path, event.name), own_user), 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), IN_CLOSE_WRITE | IN_MOVED_TO, rec=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