#!/opt/alt/python38/bin/python3.8
#
# i360-storage-new      Python script to compile rules for appropriate
#                       proactive module version.
#

import argparse
import os
from os import path
import shutil
import subprocess
import sys
import tempfile


VERSION = '5.7'
SRC = "/var/imunify360/files/proactive/rules/%s" % VERSION
DEST = "/usr/share/i360-php-opts/sigs/%s" % VERSION
TOOL = "/usr/bin/i360-storage"
MUST_HAVE_ITEMS = ('rules.yaml',
                   'params_pattern_list',
                   'rce_patterns_list')
RESULT = '.rules', '.rulesdump'


def must_have_items_check(silently_skip):
    if not path.exists(SRC):
        sys.exit(0 if silently_skip else
                 "ERROR: directory '%s' does not EXIST" % SRC)

    for item in MUST_HAVE_ITEMS:
        if not path.exists(path.join(SRC, item)):
            sys.exit(0 if silently_skip else
                     "ERROR: file '%s' is NOT FOUND in '%s' directory" % (item, SRC))


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="compile PA rules [%s -> %s]" % (SRC, DEST))
    parser.add_argument("--silent-on-noop",
                        action="store_true",
                        help="do nothing if %s does not exist" % SRC)
    args = parser.parse_args()

    must_have_items_check(args.silent_on_noop)
    tempdir = tempfile.mktemp(prefix='%s_tmpdir_' % path.basename(DEST),
                              dir=path.dirname(DEST))
    shutil.copytree(SRC, tempdir)
    os.chdir(tempdir)
    os.umask(0o022)
    try:
        subprocess.check_call([TOOL, 'mkbin'])
        subprocess.check_call([TOOL, 'mkdump', '.rules', '.rulesdump'])
    except subprocess.CalledProcessError as e:
        # full backtrace is not needed for tool call error
        sys.exit("ERROR: %s" % e)

    os.makedirs(DEST, mode=0o755, exist_ok=True)
    for item in RESULT:
        shutil.copy(path.join(tempdir, item), DEST)

    os.chdir(tempfile.gettempdir())  # chdir away from tempdir
    shutil.rmtree(tempdir)
    print("Success.")
