""" Post source files to observing CodeSonar process. """

import os
import subprocess
import sys

from gtr import gthome


CSONAR_DIR = gthome()
CS_IMPORT_DIR = os.path.join(CSONAR_DIR, 'csurf', 'src', 'front_ends')


def load_cs_import_module():
    """ Import cs-import.py and return it as a module var. """
    import importlib
    sys.path.append(CS_IMPORT_DIR)
    return importlib.import_module("cs-import")


# This function is used by import_sarif.py:
def get_source_languages():
    """ Get a sequence of language IDs that can be used for the -language option. """
    cs_import = load_cs_import_module()
    return cs_import.LANGUAGES


def main(argv):
    csonar_bin_dir = os.path.join(CSONAR_DIR, 'codesonar', 'bin')
    if '--help' in argv or '-h' in argv:
        # Special case for --help option: call cs-import in process:
        cs_import = load_cs_import_module()
        argv2 = list(argv)
        argv2[0] = f'codesonar {os.path.basename(__file__)}'
        return cs_import.main(argv2)
    metascan_argv = [
        os.path.join(csonar_bin_dir, 'cs-metascan'),
        os.path.join(csonar_bin_dir, 'cspython'),
        os.path.join(CS_IMPORT_DIR, 'cs-import.py'),
        ] + argv[1:]
    metascan_environ = dict(os.environ)
    # Prevent automatic globbing done when cspython is spawned on Windows:
    metascan_environ['CS_DISABLE_GLOB_CM_ARGS'] = '1'
    return subprocess.Popen(
            metascan_argv,
            env=metascan_environ,
        ).wait()


if __name__ == "__main__":
    sys.exit(main(sys.argv))
