#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# ============================================================================
# Copyright René Mayrhofer, 2010-2011
#
# Contributors:
# * Dieter Plaetinck: documentation and bug fixes, launcher script, config
#   handling improvements
# * René 'Necoro' Neumann: improvements for embedded Jabberbot with regards to 
#   disconnects, bug fixes
# * Philipp Tölke: Windows port
# * Olivier Guerriat : Mac OS port, Growl support
# * evgeni@golov.de: Various bugfixes
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2 or 3 of the License.
# ============================================================================

from __future__ import with_statement

__author__ = 'René Mayrhofer <rene@mayrhofer.eu.org>'
__version__ = '0.5'
__website__ = 'http://www.mayrhofer.eu.org/dvcs-autosync'
__license__ = 'GPL v2 or v3'

# Imports for various platforms and error handling concerning optional Python modules
import warnings, sys, signal, os, time, subprocess, threading, fnmatch, ConfigParser, logging

# OS detection
detected_os = False
try:
    import pyinotify
    detected_os = "LINUX"
except:
    pass
try:
    import win32api
    detected_os = "WINDOWS"
except:
    pass
try:
    from fsevents import Observer
    from fsevents import Stream
    detected_os = "MAC_OS"
except:
    pass
if not detected_os:
    logging.error('Unsupported OS, sorry.')
    sys.exit(2)


if not hasattr(subprocess, 'check_output'):
    # see https://gist.github.com/839684
    def check_output(*popenargs, **kwargs):
        if 'stdout' in kwargs:
            raise ValueError('stdout argument not allowed, it will be overridden.')
        process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs)
        output, unused_err = process.communicate()
        retcode = process.poll()
        if retcode:
            cmd = kwargs.get("args")
            if cmd is None:
                cmd = popenargs[0]
            raise subprocess.CalledProcessError(retcode, cmd)
        return output
    subprocess.check_output = check_output


# do not care about deprecation warnings right now, as they are only confusing for users
with warnings.catch_warnings():
    warnings.filterwarnings("ignore",category=DeprecationWarning)
    # need to use a private instance of jabberbot for now...
    # TODO: remove when we no longer need this
    sys.path.insert(0, '/usr/share/dvcs-autosync')
    import jabberbot, xmpp


botcmd = jabberbot.botcmd

# some global variables, will be initialized in main
desktopnotifykde = False
desktopnotifygnome = False
desktopnotifygrowl = False
xmppnotify = False
knotify = None
notifier = None
gnotify = None
bot = None
hostname = None
username = None
pidfile = None
icon = None

def printmsg(title, msg, level=logging.INFO):
    # there are probably more levels but I couldn't find the appropriate docs
    kdelevels = {logging.DEBUG: 'info',
                 logging.INFO: 'info',
                 logging.WARNING: 'warning',
                 logging.ERROR: 'warning',
                 logging.CRITICAL: 'warning'}
    try:
        if desktopnotifygnome:
            urgencies = {logging.DEBUG: pynotify.URGENCY_LOW,
                         logging.INFO: pynotify.URGENCY_NORMAL,
                         logging.WARNING: pynotify.URGENCY_CRITICAL,
                         logging.ERROR: pynotify.URGENCY_CRITICAL,
                         logging.CRITICAL: pynotify.URGENCY_CRITICAL}
            n = pynotify.Notification(title, msg)
            if icon:
		n.set_icon_from_pixbuf(icon)
            n.set_urgency(urgencies[level])
            n.show()
        elif desktopnotifykde:
            knotify.event(kdelevels[level], 'kde', [], title, msg, [], [], 0, dbus_interface="org.kde.KNotify")
        elif desktopnotifygrowl:
            gnotify.notify("Every notifications", title, msg, gnotifyIcon)
            time.sleep(0.1) # When sending multiple notifications at the same time, Growl seems to only consider the latest. This little delay prevent that.

        if xmppnotify and bot and alsonotify:
            bot.send(alsonotify, '[%s]: %s' % (title, msg))
    except:
        pass

    logging.log(level, "NOTIFICATION: %s: %s" % (title, msg))


# this helper class has been shamelessly copied from http://socialwire.ca/2010/01/python-resettable-timer-example/
class ResettableTimer(threading.Thread):
    """
    The ResettableTimer class is a timer whose counting loop can be reset
    arbitrarily. Its duration is configurable. Commands can be specified
    for both expiration and update. Its update resolution can also be
    specified. Resettable timer keeps counting until the "run" method
    is explicitly killed with the "kill" method.
    """
    def __init__(self, maxtime, expire, inc=None, update=None, arg=None):
        """
        @param maxtime: time in seconds before expiration after resetting
                        in seconds
        @param expire: function called when timer expires
        @param inc: amount by which timer increments before
                    updating in seconds, default is maxtime/2
        @param update: function called when timer updates
        @param arg: arbitrary argument that will be passed to function expire when timer expires 
        """
        self.maxtime = maxtime
        self.expire = expire
        if inc:
            self.inc = inc
        else:
            self.inc = maxtime / 2
        if update:
            self.update = update
        else:
            self.update = lambda c : None

        self.arg = arg
        self.counter = 0
        self.active = True
        self.stop = False
        threading.Thread.__init__(self)
        self.setDaemon(True)
        
    def set_counter(self, t):
        """
        Set self.counter to t.

        @param t: new counter value
        """
        self.counter = t
        
    def deactivate(self):
        """
        Set self.active to False.
        """
        self.active = False
        
    def kill(self):
        """
        Will stop the counting loop before next update.
        """
        self.stop = True
        
    def reset(self):
        """
        Fully rewinds the timer and makes the timer active, such that
        the expire and update commands will be called when appropriate.
        """
        self.counter = 0
        self.active = True

    def run(self):
        """
        Run the timer loop.
        """
        while True:
            self.counter = 0
            while self.counter < self.maxtime:
                self.counter += self.inc
                time.sleep(self.inc)
                if self.stop:
                    return
                if self.active:
                    self.update(self.counter)
            if self.active:
                self.active = False
                self.expire(self.arg)


class AutosyncJabberBot(jabberbot.JabberBot):
    def __init__(self, username, password, res=None, debug=False, ignoreownmsg=True):
        self._running = False
        self._unsent = []
        jabberbot.JabberBot.__init__(self, username, password, res, debug, False, not ignoreownmsg)
        self.PING_FREQUENCY = 30

    def _process_thread(self):
        self.log.info('Background Jabber bot thread starting')
        while self._running:
            try:
                if self.conn.Process(1) is None:
                    # Process() does not raise IOErrors
                    # instead it returns None if there is no data
                    self.log.warning('Link down')
                    raise IOError
                self.idle_proc()
            except IOError:
                self.conn = None
                self.log.warning('Received IOError while trying to handle incoming messages, trying to reconnect now')
                while not self.conn and self._running:
                    time.sleep(10)
                    self.conn = self.connect()

            # copy self._unsent, s.t. it doesn't gets an infinite loop
            # this could happen if we try to send a msg, this fails
            # and then it gets re-appended to self._unsent -- where we try
            # to send it again ... and again ... and again...
            unsent = self._unsent
            self._unsent = []
            for msg in unsent:
                self.send(*msg)

    def start_serving(self):
        self.connect()
        if self.conn:
            self.log.info('bot connected. serving forever.')
        else:
            self.log.warning('could not connect to server - aborting.')
            return

        self._running = True
        self._thread = threading.Thread(target=self._process_thread)
        self._thread.daemon = True
        self._thread.start()

        # this is a hack to get other bots to add this one to their "seen" lists
        # TODO: still doesn't work, figure out how to use JabberBot to get rid of
        # 'AutosyncJabberBot : Ignoring message from unseen guest: rene-sync@doc.to/AutosyncJabberBot on iss'
        self.conn.send(xmpp.Presence(to=username))

    def stop_serving(self):
        self._running = False
        if self._thread:
	    self._thread.join()

    def on_ping_timeout(self):
        raise IOError, "Ping timeout"

    # override the send method so that connection errors can be handled by trying to reconnect
    def send(self, user, text, in_reply_to=None, message_type='chat'):
        try:
            jabberbot.JabberBot.send(self, user, text, in_reply_to, message_type)
        except (AttributeError, IOError):
            if self.conn is not None: # error is something different
                raise
            self.log.warning('Received an error while trying to send message. Will send it later.')
            self._unsent.append((user, text, in_reply_to, message_type))
  
    @botcmd
    def whoami(self, mess, args):
        """Tells you your username"""
        return 'You are %s, I am %s/%s' % (mess.getFrom(), self.jid, self.res)

    @botcmd
    def ping(self, mess, args):
        self.log.debug('Received ping command over Jabber channel')
        return 'pong'
        
    @botcmd
    def pushed(self, mess, args):
        self.log.debug('Received pushed command over Jabber channel with args %s from %s' % (args, mess.getFrom()))
        if mess.getFrom() == str(self.jid) + '/' + self.res:
            self.log.debug('Ignoring own pushed message looped back by server')
        else:
            self.log.debug('Trying to pull from %s' % args)
            with lock:
                handler.protected_pull()

    @botcmd
    def login(self, mess, args):
        """The bot sends a "login" message first. ignore it"""
        return

    @botcmd
    def unknown(self, mess, args):
        """Should somebody say something that is not a command, all bots will
        reply with "Unknown command...." to which all bots will reply that thay
        do not know the command "Unknown"..."""
        return


class FileChangeHandler():
    def __init__(self, cwd, ignored):
        self.cwd = cwd
        self.ignored = ignored
        # singleton timer for delayed execution of push 
        self._push_timer = None
        # When set to true, then all events will be ignored.
        # This is used to temporarily disable file event handling when a local
        # pull operation is active.
        self._ignore_events = False
        # This is a dictionary of all events that occurred within _coalesce_time seconds.
        # Elements in the sets are tuples of FIFO lists of event types which were delivered
        # for the respective file path and timers for handling the file, indexed by the 
        # respective file path.
        self._file_events = dict()
        
    def _exec_cmd(self, commands, parms = None):
        j = 0
        for command in commands.split('\n'):
            cmdarray = command.split(' ')
            if parms:
                i = 0
                while i < len(cmdarray):
                    if cmdarray[i] == '%s':
                        logging.debug('Substituting cmd part %s with %s', cmdarray[i], parms[j])
                        cmdarray[i] = parms[j]
                        j=j+1
                    i=i+1 
            try:
                out = subprocess.check_output(cmdarray, cwd=self.cwd, stderr=subprocess.STDOUT)
                logging.debug("Command '%s' in '%s'. Output:\n%s" % (" ".join (cmdarray), self.cwd, out))
            except subprocess.CalledProcessError, e:
	        if hasattr(e, 'output'):
		    printmsg('Command failed', "Command '%s' in '%s' failed.  Output:\n%s" % (" ".join (cmdarray), self.cwd, e.output), level=logging.WARNING)
		else:
		    printmsg('Command failed', "Command '%s' in '%s' failed." % (" ".join (cmdarray), self.cwd), level=logging.WARNING)

    def _post_action_steps(self, curpath = None):
        with lock:
            # the status command should return 0 when nothing has changed
            retcode = subprocess.call(cmd_status, cwd=self.cwd, shell=True)
            if retcode != 0:
                if curpath:
                    commitmsg = 'Autocommit of file %s changed on host %s' % (curpath, hostname)
                else:
                    commitmsg = 'Autocommit of all changes since last autosync startup on host %s' % hostname
                self._exec_cmd(cmd_commit, [commitmsg])

        if retcode != 0 and syncmethod != 'none':
            # reset the timer and start in case it is not yet running (start should be idempotent if it already is)
            # this has the effect that, when another change is committed within the timer period (readfrequency seconds),
            # then these changes will be pushed in one go
            if self._push_timer and self._push_timer.is_alive():
                logging.debug('Resetting already active push timer to new timeout of %s seconds until push would occur', readfrequency)
                self._push_timer.reset()
            else:
                logging.debug('Starting push timer with %s seconds until push would occur (if no other changes happen in between)', readfrequency)
                self._push_timer = ResettableTimer(maxtime=readfrequency, expire=self._real_push, inc=1, update=self.timer_tick)
                self._push_timer.start()
        else:
            logging.debug('%s reported that there is nothing to commit, not touching commit timer' % cmd_commit.split(' ')[0])

    def _queue_action(self, event, action, parms, act_on_dirs=False):
        curpath = event.pathname
        if self._ignore_events:
            logging.debug('Ignoring event %s to %s, it is most probably caused by a remote change being currently pulled', event.maskname, event.pathname)
            return
        if event.dir and not act_on_dirs:
            logging.debug('Ignoring change to directory %s', curpath)
            return
        if any(fnmatch.fnmatch(curpath, pattern) for pattern in self.ignored):
            logging.debug('Ignoring change to file %s because it matches the ignored patterns from .gitignore', curpath)
            return

        # remember the event for this file, but don't act on it immediately
        # this allows e.g. a file that has just been removed and re-created
        # immediately afterwards (as many editors do) to be recorded just as
        # being modified
        with lock:
            # each entry in the dict is a tuple of the list of events and a timer
            if not self._file_events.has_key(curpath):
                self._file_events[curpath] = [list(), None]
            # and each entry in the list is a tuple of event name and associated action
            self._file_events[curpath][0].append((event.maskname, action))
            if self._file_events[curpath][1] and self._file_events[curpath][1].is_alive():
                logging.debug('Resetting already active coalesce timer to new timeout of %s seconds until coalescing events for file %s would occur', coalesce_seconds, curpath)
                self._file_events[curpath][1].reset()
            else:
                logging.debug('Starting coalesce timer with %s seconds until coalescing events for file %s would occur (if no other changes happen in between)', coalesce_seconds, curpath)
                self._file_events[curpath][1] = ResettableTimer(maxtime=coalesce_seconds, expire=self._filter_and_handle_actions, inc=1, arg=[curpath, parms])
                self._file_events[curpath][1].start()
            
    def _filter_and_handle_actions(self, args):
        curpath = args[0]
        parms = args[1]
            
        logging.info('Coalesce event triggered for file %s', curpath)
        with lock:
            logging.debug('Considering file %s, which has the following events recorded:', curpath)
            events, timer = self._file_events[curpath]
            lastevent = None
            lastaction = None
            for eventtype, action in events:
                logging.debug('   Event type=%s, action=%s', eventtype, action)
                
                if not lastevent:
                    lastevent = eventtype
                    lastaction = action
                
                # prio 1: add
                # prio 2: move
                # prio 3: modify
                # prio 4: rm
                # special case: rm then add --> modify
                if lastevent == 'IN_DELETE' and eventtype == 'IN_CREATE':
                    lastevent = 'IN_MODIFY'
                    lastaction = cmd_modify
                    break
                
                # priority ordering 
                if lastevent == 'IN_MODIFY' and eventtype == 'IN_CREATE':
                    lastevent = eventtype
                    lastaction = action
                if lastevent == 'IN_DELETE' and eventtype == 'IN_MODIFY':
                    lastevent = eventtype
                    lastaction = action

            logging.info('Final action for file %s: type=%s, action=%s', curpath, lastevent, lastaction)

            # and clear again for next events coalescing
            del self._file_events[curpath]
            
            printmsg('Local change', 'Committing changes in %s: %s' % (curpath, lastaction))
    
            self._exec_cmd(lastaction, parms)
            self._post_action_steps(curpath)
            
    def timer_tick(self, counter):
        logging.debug('Tick %d / %d' % (counter, self._push_timer.maxtime))

    def startup(self):
        with lock:
            logging.info('Running startup command to check for local changes now: %s', cmd_startup)
            self._exec_cmd(cmd_startup)
            self._post_action_steps()

    def _real_push(self, arg):
        proc = subprocess.Popen(cmd_remoteurl.split(' '), stdout=subprocess.PIPE, cwd=self.cwd)
        (remoteurl, errors) = proc.communicate()
        printmsg('Pushing changes', 'Pushing last local changes to remote repository %s' % remoteurl)
        
        with lock:
            # TODO: check if we actually need a pull or a check-for-pull here 
            # or if all race conditions were already ruled out
            # if we need a check-for-pull, then something like 
            #    git fetch --dry-run | grep "Unpacking objects:
            # might help
            #self.protected_pull()
            self._exec_cmd(cmd_push)

        # and try to notify other instances
        if bot:
            bot.send(username, 'pushed %s' % remoteurl)

    def protected_pull(self):
        printmsg('Pulling changes', 'Pulling changes from remote repository')
        # need to handle file change notification while applying remote
        # changes caused by the pull: either conservative (ignore all
        # file notifications while the pull is running) or optimized (replay the
        # file changes that were seen during the pull after it has finished)

        if conservative_pull_lock:
            # conservative strategy: ignore all events from now on
            self._ignore_events = True

        with lock:
            handler._exec_cmd(cmd_pull)

        if conservative_pull_lock:
            # pull done, now start handling events again
            self._ignore_events = False
            # and handle those local changes that might have happened while the
            # pull ran and we weren't listening by simply doing the startup 
            # sequence again
            self.startup()


# The definition of this class has to be OS arbitrated because pyinotify can't be
# imported under windows and inheriting from pyinotify.ProcessEvent needs it...
if detected_os == "LINUX":
    class LinuxFileChangeHandlerAdapter(pyinotify.ProcessEvent):
        def my_init(self, handler):
            self.handler = handler

        def process_IN_DELETE(self, event):
            # sanity check - don't remove file if it still exists in the file system!
            if os.path.exists(event.pathname):
                logging.debug('Ignoring file delete event on %s, as it still exists - it was probably immediately re-created by the application', event.pathname)
                return
             
            self.handler._queue_action(event, cmd_rm, [event.pathname])

        def process_IN_CREATE(self, event):
	    # sanity check - don't add file if it (no longer) exists in the file system!
	    if not os.path.exists(event.pathname):
		logging.debug('Ignoring file create event on %s, as it (no longer) exists - it was probably created as a temporary file and immediately removed by the application', event.pathname)
		return

	    self.handler._queue_action(event, cmd_add, [event.pathname])

        def process_IN_MODIFY(self, event):
            self.handler._queue_action(event, cmd_modify, [event.pathname])

        def process_IN_CLOSE_WRITE(self, event):
            self.handler._queue_action(event, cmd_modify, [event.pathname])

        def process_IN_ATTRIB(self, event):
            self.handler._queue_action(event, cmd_modify, [event.pathname])

        def process_IN_MOVED_TO(self, event):
            try:
                if event.src_pathname:
                    logging.debug('Detected moved file from %s to %s', event.src_pathname, event.pathname)
                    self._handler.queue_action(event, cmd_move, [event.src_pathname, event.pathname], act_on_dirs=True)
                else:
                    logging.debug('Moved file to %s, but unknown source, will simply add new file', event.pathname)
                    self.handler._queue_action(event, cmd_add, [event.pathname], act_on_dirs=True)
            except AttributeError:
                # we don't even have the attribute in the event, so also add
                logging.debug('Moved file to %s, but unknown source, will simply add new file', event.pathname)
                self.handler._queue_action(event, cmd_add, [event.pathname], act_on_dirs=True)


if detected_os == "WINDOWS":
    class WindowsFileChangeHandlerAdapter(threading.Thread):
	def __init__(self, path, ignoreabsolutepaths, handler):
	    threading.Thread.__init__(self)
	    self.handler = handler
	    self.ignoreabsolutepaths = ignoreabsolutepaths
	    self.path = path

	# This is to mimic the event-type of inotify
	class MyEvent():
	    def __init__(self, dir, pathname, action):
		self.dir = dir
		self.pathname = pathname
		self.maskname = [ "", "IN_CREATE", "IN_DELETE", "IN_MODIFY", "IN_DELETE", "IN_CREATE"][action]

	def run(self):
	    import win32file, win32con

	    FILE_LIST_DIRECTORY = 0x0001

	    path_to_watch = self.path
	    hDir = win32file.CreateFile (
	      path_to_watch,
	      FILE_LIST_DIRECTORY,
	      win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
	      None,
	      win32con.OPEN_EXISTING,
	      win32con.FILE_FLAG_BACKUP_SEMANTICS,
	      None
	    )

	    while 1:
		results = win32file.ReadDirectoryChangesW (
			hDir,
			1024,
			True,
			win32con.FILE_NOTIFY_CHANGE_FILE_NAME |
			win32con.FILE_NOTIFY_CHANGE_DIR_NAME |
			win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES |
			win32con.FILE_NOTIFY_CHANGE_SIZE |
			win32con.FILE_NOTIFY_CHANGE_LAST_WRITE |
			win32con.FILE_NOTIFY_CHANGE_SECURITY,
			None,
			None
			)
		for action, file in results:
		    full_filename = os.path.join (path_to_watch, file)

		    #check if this file is ignored:
		    if True in [x in full_filename for x in self.ignoreabsolutepaths]:
			continue

		    event = self.MyEvent(os.path.isdir(file), file, action)
		    if action == 1 or action == 5: #CREATE or MOVE_TO
			self.handler._queue_action(event, cmd_add, [event.pathname])
		    elif action == 2 or action == 4: #DELETE or MOVE_FROM
			if os.path.exists(event.pathname):
			    logging.debug('Ignoring file delete event on %s, as it still exists - it was probably immediately re-created by the application', event.pathname)
			    continue
			self.handler._queue_action(event, cmd_rm, [event.pathname])
		    elif action == 3: #MODIFY:
			self.handler._queue_action(event, cmd_modify, [event.pathname])


if detected_os == "MAC_OS":
    class MacOSFileChangeHandlerAdapter(threading.Thread):
    	def __init__(self, path, ignoreabsolutepaths, handler):
    	    threading.Thread.__init__(self)
    	    self.handler = handler
    	    self.ignoreabsolutepaths = ignoreabsolutepaths
    	    self.path = path
    
    	# This is to mimic the event-type of inotify
    	class MyEvent():
    	    def __init__(self, dir, pathname, action):
    		self.dir = dir
    		self.pathname = pathname
    		masks = {   # from doc : http://developer.apple.com/library/mac/#documentation/Darwin/Reference/FSEvents_Ref/FSEvents_h/index.html#HeaderDoc_enums
    		            256:"IN_CREATE", # created
    		            512:"IN_DELETE", # removed
    		            # in doc, but don't seem to be used, included to prevent potential bug
    		            2048:"IN_MODIFY", # renamed
    		            4096:"IN_MODIFY", # modified
    		            0x00000400:'InodeMetaMod',
    		            0x00002000:'FinderInfoMod',
    		            0x00004000:'ChangeOwner',
    		            0x00008000:'XattrMod',
    		            # not in doc, but actually used
    		            64:"IN_DELETE", # before rename
    		            128:"IN_CREATE", # after rename
    		            2:"IN_MODIFY",
    		        }
    		self.maskname = masks[action]
    		print self.maskname
        
        def __call__(self, event):
            for ignoreabsolutepath in self.ignoreabsolutepaths:
                if event.name.startswith(ignoreabsolutepath):
                    return
                    
            event = self.MyEvent(os.path.isdir(event.name), event.name, event.mask)
            
            if event.maskname == "IN_CREATE": #CREATE or MOVE_TO
                self.handler._queue_action(event, cmd_add, [event.pathname], act_on_dirs=True)
            elif event.maskname == "IN_DELETE": #DELETE or MOVE_FROM
                if os.path.exists(event.pathname):
                    logging.debug('Ignoring file delete event on %s, as it still exists - it was probably immediately re-created by the application', event.pathname)
                    return
                self.handler._queue_action(event, cmd_rm, [event.pathname], act_on_dirs=True)
            elif event.maskname == "IN_MODIFY": #MODIFY:
                self.handler._queue_action(event, cmd_modify, [event.pathname], act_on_dirs=True)
        
    	def run(self):
    	    
    	    observer = Observer()
            observer.start()

            #handler = self.process_event(self)
            
            stream = Stream(self, self.path, file_events=True)
            observer.schedule(stream)

def initialize_win32notify(path, ignoreabsolutepaths, handler): # Windows
    adapter = WindowsFileChangeHandlerAdapter(path, ignoreabsolutepaths, handler)
    adapter.daemon = True
    adapter.start()

def initialize_fsevents(path, ignoreabsolutepaths, handler): # Mac OS
    adapter = MacOSFileChangeHandlerAdapter(path, ignoreabsolutepaths, handler)
    adapter.daemon = True
    adapter.start()

def initialize_inotify(ignoreabsolutepaths, path, ignorefilepatterns, readfrequency, handler): # Linux
    excl = pyinotify.ExcludeFilter(ignoreabsolutepaths)
    wm = pyinotify.WatchManager()
    # TODO: frequency doesn't work....
    notifier = pyinotify.ThreadedNotifier(wm, LinuxFileChangeHandlerAdapter(handler = handler), read_freq=readfrequency)
    #notifier = pyinotify.ThreadedNotifier(wm, handler)
    # coalescing events needs pyinotify >= 0.9, so make this optional
    try:
        notifier.coalesce_events()
    except AttributeError as e:
        logging.warning('Cannot coalesce events, pyinotify does not seem to support it (maybe too old): %s', e)
    mask = pyinotify.IN_DELETE | pyinotify.IN_CREATE | pyinotify.IN_CLOSE_WRITE | pyinotify.IN_ATTRIB | pyinotify.IN_MOVED_FROM | pyinotify.IN_MOVED_TO | pyinotify.IN_DONT_FOLLOW | pyinotify.IN_ONLYDIR
    try:
        logging.debug('Adding recursive, auto-adding watch for path %s with event mask %d', path, mask)
        wd = wm.add_watch(path, mask, rec=True, auto_add=True, quiet=False, exclude_filter=excl)
        if wd <= 0:
            logging.warning('Unable to add watch for path %s - this will not work', path)
    except pyinotify.WatchManagerError, e:
        logging.warning("pyinotify.WatchManagerError: %s, %s", e, e.wmd)

    logging.info('Start monitoring %s (type c^c to exit)', path)
    notifier.start()


def config_get (section, option, optional=False):
    ret = None
    try:
        ret = config.get(section, option)
    except ConfigParser.NoSectionError:
        if not optional:
            printmsg ("Configuration error", "Could not load section %s from configuration at %s" % (section, config_locations), level=logging.ERROR)
            sys.exit(2)
    except ConfigParser.NoOptionError:
        if not optional:
            printmsg ("Configuration error", "Could not load option %s from section %s from configuration at %s" % (option, section, config_locations), level=logging.ERROR)
            sys.exit(2)
    except ConfigParser.ParsingError:
        printmsg ("Configuration error", "Could not parse configuration at %s" % config_locations, level=logging.ERROR)
        sys.exit(2)
    return ret


def signal_handler(signal, frame):
    logging.info('You pressed Ctrl+C, exiting gracefully!')
    if notifier:
        notifier.stop()
    if bot:
        bot.stop_serving()

    # also remove the pidfile after a clean shutdown
    if pidfile and os.path.exists(pidfile):
	os.remove(pidfile)
        
    sys.exit(0)


if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    
    # try to set up desktop notification, first for KDE4, then for Gnome
    # the signature is not correct, so rely on pynotify only at the moment
    #try:
	#import dbus
	#knotify = dbus.SessionBus().get_object("org.kde.knotify", "/Notify")
	#knotify.event("warning", "autosync application", [],
	    #'KDE4 notification initialized', 'Initialized KDE4 desktop notification via DBUS',
	    #[], [], 0, dbus_interface='org.kde.KNotify')
	#desktopnotifykde = True
    #except:
	#print 'KDE4 KNotify does not seem to run or dbus is not installed'
    try:
        import pynotify, gtk
        try:
	    icon = gtk.IconTheme().load_icon('dvcs-autosync', 48, gtk.ICON_LOOKUP_GENERIC_FALLBACK)
	except:
	    icon = None
        if pynotify.init('autosync application'):
            logging.info('pynotify initialized successfully, will use desktop notifications')
            desktopnotifygnome = True
        else:
            logging.warning('there was a problem initializing the pynotify module')
    except:
        logging.info('pynotify does not seem to be installed')

    try:
        import Growl
        gnotifyImagePath = os.path.abspath('/usr/share/icons/hicolor/48x48/apps/dvcs-autosync.png')
        if os.path.exists(gnotifyImagePath):
            gnotifyIcon = Growl.Image.imageFromPath(gnotifyImagePath)
        else:
            gnotifyIcon = None
        gnotify = Growl.GrowlNotifier( "AutoSync", ["Every notifications"], applicationIcon=gnotifyIcon)
        gnotify.register()
        logging.info('Growl initialized successfully, will use desktop notifications')
        desktopnotifygrowl = True
    except:
        logging.info('Growl does not seem to be installed')


    config = ConfigParser.RawConfigParser()
    defaultcfgpath = os.path.expanduser('~/.autosync')
    if len(sys.argv) >= 2:
        config_locations = [sys.argv[1], defaultcfgpath]
    else:
        config_locations = [defaultcfgpath]
    read_configfiles = config.read(config_locations)
    if len(read_configfiles) == 0:
	logging.error('No config file specified or config file(s) %s could not be opened' % config_locations)
	sys.exit(10)

    pathstr = config_get('autosync', 'path')
    path = os.path.normpath(os.path.expanduser(pathstr))
    if os.path.isdir(path):
        logging.info('Watching path %s', path)
    else:
        logging.error('path %s (expanded from %s) does not exist', path, pathstr)
        sys.exit(100)
    
    # ensure that the script is not running twice with the same config file
    pidfile = config_get('autosync', 'pidfile', optional=True)
    if not pidfile:
	# default pidfile name if not specified in config
	pidfile = read_configfiles[0] + '.pid'
    pidfile = os.path.normpath(os.path.expanduser(pidfile))
    logging.debug('Checking/writing pidfile %s' % pidfile)
    # does the file already exist?
    if os.access(pidfile, os.F_OK):
	# check if a process with that PID is still running
	pidfd = open(pidfile)
	pidfd.seek(0)
        old_pid = pidfd.readline()
        # Now we check the PID from lock file matches to the current
        # process PID
        if os.path.exists("/proc/%s" % old_pid):
	    logging.error('DVCS-autosync already running with config file %s under PID %s, exiting now' % (read_configfiles[0], old_pid))
            sys.exit(9)
        else:
	    logging.warning('PID file %s already exists, but no process seems to be running, removing file now' % pidfile)
	    os.remove(pidfile)
    # if we get to here, process is not running and pidfile doesn't exist (anymore)
    cur_pid = str(os.getpid())
    pidfd = open(pidfile, 'w')
    pidfd.write(cur_pid)
    pidfd.close()
    
    ignorepaths = config_get('autosync', 'ignorepath')
    readfrequency = int(config_get('autosync', 'readfrequency'))
    coalesce_seconds = 2
    syncmethod = config_get('autosync', 'syncmethod')
    
    # in the upper pynotify try, the desktopnotify options are set, but can override here
    notifymethod = config_get('autosync', 'notifymethod', optional=True)
    if not notifymethod or notifymethod == 'desktop':
	xmppnotify = False
	logging.info('Using only desktop notification')
    elif notifymethod == 'xmpp':
	xmppnotify = True
	desktopnotifygnome = False
	desktopnotifykde = False
	desktopnotifygrowl = False
	logging.info('Using only XMPP notification')
    elif notifymethod == 'all':
	xmppnotify = True
	logging.info('Using all notification methods')
    elif notifymethod == 'none':
	xmppnotify = False
	desktopnotifygnome = False
	desktopnotifykde = False
	desktopnotifygrowl = False
	logging.info('Disabling all notification methods, will only log to console')
    else:
	logging.warning('Unknown notifymethod "%s" configured, will keep default (desktop)', notifymethod)
    
    pulllock = config_get('autosync', 'pulllock')
    if pulllock == 'conservative':
        conservative_pull_lock = True
    elif pulllock == 'optimized':
        conservative_pull_lock = False
        logging.error('Optimized pull strategy not fully implemented yet (event replay queue missing)')
        sys.exit(101)
    else:
        logging.error('Unknown pull lock strategy %s, please use either conservative or optimized', pulllock)
        sys.exit(100)    
    
    # Read required DVCS commands
    cmd_status = config_get('dvcs', 'statuscmd')
    cmd_startup = config_get('dvcs', 'startupcmd')
    cmd_commit = config_get('dvcs', 'commitcmd')
    cmd_push = config_get('dvcs', 'pushcmd')
    cmd_pull = config_get('dvcs', 'pullcmd')
    cmd_add = config_get('dvcs', 'addcmd')
    cmd_rm = config_get('dvcs', 'rmcmd')
    cmd_modify = config_get('dvcs', 'modifycmd')
    cmd_move = config_get('dvcs', 'movecmd')
    cmd_remoteurl = config_get('dvcs', 'remoteurlcmd')
    
    # TODO: this is currently git-specific, should be configurable
    ignorefile = os.path.join(path, '.gitignore')
    # load the patterns and match them internally with fnmatch
    if os.path.exists(ignorefile):
        f = open(ignorefile, 'r')
        ignorefilepatterns = [pat.strip() for pat in f.readlines()]
        f.close()
    else:
        ignorefilepatterns = []
    # (unfortunately, can't use pyinotify.ExcludeFilter, because this expects regexes (which .gitignore doesn't support))
    logging.info('Ignoring files matching any of the patterns %s', ' '.join(ignorefilepatterns))

    # but we can use the ignore filter with our own pathname excludes
    # However, need to prepend the watch path name, as the excludes need to be 
    # absolute path names.
    ignoreabsolutepaths = [os.path.normpath(path + os.sep + ignorepath) for ignorepath in ignorepaths.split()]
    logging.info('Adding list to inotify exclude filter: %s', ignoreabsolutepaths)

    signal.signal(signal.SIGINT, signal_handler)

    if syncmethod == 'xmpp':
	username = config_get('xmpp', 'username')
	password = config_get('xmpp', 'password')
	alsonotify = config_get('xmpp', 'alsonotify', optional=True)
	if xmppnotify and not alsonotify:
	    logger.warning('XMPP notification requested, but alsonotify option not configured, will not send XMPP notifications')

	if (detected_os == "LINUX") or (detected_os == "MAC_OS"):
	    hostname = os.uname()[1]
	elif detected_os == "WINDOWS":
	    hostname = win32api.GetComputerName()
	else:
	    hostname = "UNSUPPORTED_OS"
	
	res = 'AutosyncJabberBot on %s' % hostname
	try:
	    with warnings.catch_warnings():
		warnings.filterwarnings("ignore",category=DeprecationWarning)
		bot = AutosyncJabberBot(username, password, res=res, debug=False, ignoreownmsg=False)
		bot.start_serving()
	    bot.send(username, 'login %s' % res)
	    printmsg('Autosync Jabber login successful', 'Successfully logged into account %s' % username)
	except Exception as e:
	    logging.error("Exception %s: %s", type(e), e)
	    printmsg('Autosync Jabber login failed', 'Could not login to Jabber account %s. Will not announce pushes to other running autosync instances.' % username)
    elif syncmethod == 'autosync-server':
        logging.error('Alternative autosync-server sync method not fully implemented yet')
        sys.exit(101)
    elif syncmethod == 'none':
	logging.info('Synchronization method none configured, will not attempt to synchronize with any repository')
    else:
	printmsg('No synchronization method configured', 'No or unknown syncmethod configured, will not attempt to synchronize with any repository', level=logging.WARNING)


    printmsg('autosync starting', 'Initialization of local file notifications and Jabber login done, starting main loop')

    handler = FileChangeHandler(cwd=path, ignored=ignorefilepatterns)

    # this is a central lock for guarding repository operations
    lock = threading.RLock()

    if detected_os == "LINUX":
        initialize_inotify(ignoreabsolutepaths, path, ignorefilepatterns, readfrequency, handler)
    elif detected_os == "WINDOWS":
        initialize_win32notify(path, ignoreabsolutepaths, handler)
    elif detected_os == "MAC_OS":
        initialize_fsevents(path, ignoreabsolutepaths, handler)
    else:
        pass #TODO

    logging.info('Executing startup synchronizaion')
    if syncmethod != 'none':
	handler.protected_pull()
	
    if not conservative_pull_lock or syncmethod == 'none':
        # only need to run the startup command here when not using conservative pull locking - otherwise the protected_pull will already do it
        handler.startup()
    
    logging.info('----------------------------------------------------------------')

    while True:
        time.sleep(10)
