#!/usr/bin/python
#
# The MIT License (MIT)
#
# Copyright (c) 2013 Kristoffer Gronlund
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

import argparse
import os
import sys
import string
import subprocess

try:
    import pyinotify
except Exception, e:
    print >> sys.stderr, e
    print "Install the pyinotify module"
    sys.exit(1)


DEFAULT_CMD = "echo $1"
VERBOSE = False


class Handler(pyinotify.ProcessEvent):
    """inotify event handler"""
    def __init__(self, cmd):
        pyinotify.ProcessEvent.__init__(self)
        self.cmd = cmd

    def process_IN_CLOSE_WRITE(self, event):
        filnam = event.pathname
        cmd = string.replace(self.cmd, "$1", '"%s"' % (filnam))
        if VERBOSE:
            print filnam, ":", cmd
        subprocess.call(cmd, shell=True)


def main():
    global VERBOSE
    parser = argparse.ArgumentParser(
        description="Execute commands when files in a directory changes",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('-c', '--cmd', dest='cmd',
                        type=str, default=DEFAULT_CMD,
                        help="command to execute when files change. "
                        "Use $1 to pass file as argument.")
    parser.add_argument('-v', '--verbose', dest='verbose', action='store_true',
                        help="Verbose output")
    parser.add_argument('dirs', metavar='dirs', type=str, nargs='+',
                        help='directories to watch')
    args = parser.parse_args()

    VERBOSE = args.verbose

    for d in (d for d in args.dirs if not os.path.isdir(d)):
        print >> sys.stderr, "Not a directory:", d
        parser.print_usage()
        sys.exit(1)

    wm = pyinotify.WatchManager()
    notifier = pyinotify.Notifier(wm, Handler(args.cmd))
    for d in args.dirs:
        wm.add_watch(d, pyinotify.IN_CLOSE_WRITE, rec=False)
        if VERBOSE:
            print "watching", d, "for changes"
    notifier.loop()

if __name__ == "__main__":
    main()
