# SPDX-License-Identifier: Apache-2.0
# Copyright 2016 The Meson development team

# ignore all lints for this file, since it is run by python2 as well

# type: ignore
# pylint: disable=deprecated-module

import json, os, subprocess, sys
from compileall import compile_file

quiet = int(os.environ.get('MESON_INSTALL_QUIET', 0))

def compileall(files):
    for f in files:
        # f is prefixed by {py_xxxxlib}, both variants are 12 chars
        # the key is the middle 10 chars of the prefix
        key = f[1:11].upper()
        f = f[12:]

        ddir = None
        fullpath = absf = os.environ['MESON_INSTALL_DESTDIR_'+key] + f
        f = os.environ['MESON_INSTALL_'+key] + f

        if absf != f:
            ddir = os.path.dirname(f)

        if os.path.isdir(absf):
            for root, _, files in os.walk(absf):
                if ddir is not None:
                    ddir = root.replace(absf, f, 1)
                for dirf in files:
                    if dirf.endswith('.py'):
                        fullpath = os.path.join(root, dirf)
                        compile_file(fullpath, ddir, force=True, quiet=quiet)
        else:
            compile_file(fullpath, ddir, force=True, quiet=quiet)

def run(manifest):
    data_file = os.path.join(os.path.dirname(__file__), manifest)
    with open(data_file, 'rb') as f:
        dat = json.load(f)
    compileall(dat)

if __name__ == '__main__':
    manifest = sys.argv[1]
    run(manifest)
    if len(sys.argv) > 2:
        optlevel = int(sys.argv[2])
        # python2 only needs one or the other
        if optlevel == 1 or (sys.version_info >= (3,) and optlevel > 0):
            subprocess.check_call([sys.executable, '-O'] + sys.argv[:2])
        if optlevel == 2:
            subprocess.check_call([sys.executable, '-OO'] + sys.argv[:2])
