#!/usr/bin/python3

import shlex
import subprocess
import logging
import traceback
from GRMConst import FOLDER

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s :%(message)s")

logger = logging.getLogger(__name__)

def log(msg):
    logger.info(msg)

def update(event):
    cmd = '/usr/bin/php /var/www/html/bin/update_info.php -d {0}'.format(event[0])
    args = shlex.split(cmd)
    proc = subprocess.run(args,stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
    log(proc.stdout.decode('utf8'))

def mainloop():
    cmd = '/usr/bin/inotifywait -r -m -e CREATE -e DELETE -e CLOSE_WRITE {0}'.format(FOLDER)
    args = shlex.split(cmd)
    p = subprocess.Popen(args,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
    for line in iter(p.stdout.readline,''):
        try:
            l = line.decode('utf-8').rstrip()
            event = l.split()
            if len(event) < 2:
                log(l)
                continue
            elif event[1] == 'CREATE,ISDIR':
                update(event)
            elif event[1] == 'DELETE,ISDIR':
                update(event)
            elif event[1] == 'DELETE':
                update(event)
            elif event[1] == 'CLOSE_WRITE,CLOSE':
                if event[2] != '.ftpquota':
                    update(event)
            else:
                log(l)
        except:
            log(traceback.format_exc())


mainloop()
