#!/usr/bin/env python

import watchdog
import time
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
from subprocess import call
import os
import sys
import argparse
import signal
import subprocess

signal.signal(signal.SIGTTOU, signal.SIG_IGN)

class PathEventHandler(PatternMatchingEventHandler):

    def __init__(self, patterns, command):
        super(PathEventHandler, self).__init__(
            patterns = patterns,
            case_sensitive = True)
        self.command = command

    def on_any_event(self, event):
        call([os.getenv('SHELL'), '-i', '-c', self.command])
        os.tcsetpgrp(0, os.getpgrp())

def watch(path, command):

    patterns = []

    if os.path.isdir(path):
        patterns.append('*')
    else:
        file_path = path
        path = os.path.dirname(path)
        patterns.append(os.path.abspath(file_path))

    path = os.path.abspath(path)

    event_handler = PathEventHandler(patterns, command)
    observer = Observer()
    observer.schedule(event_handler, path=path, recursive=True)

    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()

    observer.join()

if __name__ == '__main__':

    parser = argparse.ArgumentParser(description='Execute command on file or folder event')
    parser.add_argument('path', help='watched file or folder')
    parser.add_argument('command', help='command to execute')

    args = parser.parse_args()

    watch(args.path, args.command)
