#!/home/fadi/projects/tree-guardian/venv/bin/python

import sys
import argparse

from subprocess import Popen
from threading import Event

from tree_guardian import observe, constants


def main():
    parser = argparse.ArgumentParser(
        description='Observe directory and trigger callback on change detection'
    )
    parser.add_argument(
        '-d',
        '--debug',
        dest='debug',
        action='store_true',
        help='run observe on debug mode; it also displays all trigger-command output'
    )
    parser.add_argument(
        '-c',
        '--cmd',
        '--command',
        '--callback',
        '--callback-command',
        dest='callback_command',
        type=str,
        required=True,
        nargs='*',
        help='trigger command'
    )
    parser.add_argument(
        '-p',
        '--path',
        dest='path',
        type=str,
        required=False,
        default='.',
        help='the observable root path'
    )
    parser.add_argument(
        '-e',
        '--exclude',
        dest='exclude',
        type=str,
        required=False,
        nargs='*',
        default=constants.EXCLUDE_RECOMMENDED,
        help='excluded files from observe'
    )
    args = parser.parse_args()

    if not args.debug:
        sys.stdout = open('/dev/null', 'w')

    def callback_command(cmd: str):
        Popen(
            args=cmd,
            shell=True,
            stdout=sys.stdout,
            stderr=sys.stderr
        ).communicate()

    event = Event()
    try:
        observe(
            callback=lambda: callback_command(' '.join(args.callback_command)),
            path=args.path,
            exclude=args.exclude,
            run_async=False
        )
    except KeyboardInterrupt:
        pass
    finally:
        event.set()

    return 0


if __name__ == '__main__':
    sys.exit(main())
