#!/usr/bin/env python3
'''Monitor the ftp directory and correct the permissions of new files.'''

directory = '/srv/ftp'

import os
import stat
import pyinotify

def correct_permissions(path):
    filemode = stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH
    dirmode = filemode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
    try:
        if os.path.isdir(path):
            return(os.chmod(path, dirmode))
        else:
            return(os.chmod(path, filemode))
    except BaseException as e:
        print(e)

mask = pyinotify.IN_CREATE | pyinotify.IN_ATTRIB

class EventHandler(pyinotify.ProcessEvent):
    def process_IN_CREATE(self, event): return(correct_permissions(event.pathname))
    def process_IN_ATTRIB(self, event): return(correct_permissions(event.pathname))

if __name__ == '__main__':
    wm = pyinotify.WatchManager()
    handler = EventHandler()
    notifier = pyinotify.Notifier(wm, handler)
    wdd = wm.add_watch(directory, mask, rec=True, auto_add=True)
    notifier.loop()
    quit()
