#!/usr/bin/env python

import argparse
import logging
import os

import inotify.adapters

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='watchdir')

    parser.add_argument('dir', help='directory to watch')
    parser.add_argument('-o', '--output', help='filename of output log')

    args = parser.parse_args()

    notifier = inotify.adapters.Inotify()
    notifier.add_watch(args.dir)

    logger = logging.getLogger('watchdir')
    logger.setLevel(logging.DEBUG)

    if args.output is None:
        handler = logging.StreamHandler()
    else:
        handler = logging.FileHandler(filename=args.output)

    handler.setLevel(logging.DEBUG)

    formatter = logging.Formatter('%(asctime)s: %(message)s',
                                  '%Y%m%d.%H%M%S')
    handler.setFormatter(formatter)

    logger.addHandler(handler)

    for event in notifier.event_gen():
        if event is not None:
            #print(event)      # uncomment to see all events generated
            for e in event[1]:
                logger.info(f'{e}: {event[3]}')
                #print(f'{e}: {event[2]}')
            #if 'IN_MOVED_TO' in event[1]:
            #    print("file '{0}' moved to '{1}'".format(event[3], event[2]))
