#!/usr/bin/python3
# Copyright 2023 Collabora Ltd.
# SPDX-License-Identifier: MIT

import os
import shutil
import sys
import sysconfig
from typing import NoReturn


DEB_HOST_ARCH = 'amd64'
DEB_HOST_GNU_TYPE = 'x86_64-linux-gnu'
DEB_HOST_MULTIARCH = 'x86_64-linux-gnu'
GET_NEEDED = '/usr/libexec/gobject-introspection-bin/elf-get-needed'
TOOL = 'g-ir-doc-tool'
TOOL_PATH = '/usr/bin/g-ir-doc-tool'

ME = f'{DEB_HOST_GNU_TYPE}-{TOOL}'


class CrossGirTool:
    def __init__(
        self,
        argv: list[str],
    ) -> None:
        self.argv = argv

    def can_run(self) -> bool:
        # Assume that the Python architecture is the native architecture,
        # therefore anything different will need qemu
        python_arch = sysconfig.get_config_var('MULTIARCH')

        if python_arch == DEB_HOST_MULTIARCH:
            return True

        if {
            'i386-linux-gnu': 'x86_64-linux-gnu',
        }.get(DEB_HOST_MULTIARCH) == python_arch:
            return True

        return False

    def find_qemu(self) -> str:
        qemu = shutil.which(f'qemu-{DEB_HOST_ARCH}')

        if qemu is not None:
            return qemu

        qemu = shutil.which(f'qemu-{DEB_HOST_ARCH}-static')

        if qemu is not None:
            return qemu

        raise SystemExit(f'{ME}: Cannot find qemu-{DEB_HOST_ARCH}(-static)')

    def exec(self) -> NoReturn:
        if 'CC' not in os.environ:
            os.environ['CC'] = f'{DEB_HOST_GNU_TYPE}-gcc'

        if 'PKG_CONFIG' not in os.environ:
            os.environ['PKG_CONFIG'] = f'{DEB_HOST_GNU_TYPE}-pkgconf'

        paths = os.environ.get('GI_GIR_PATH', '').split(':')
        paths = [p for p in paths if p]
        paths.append(f'/usr/lib/{DEB_HOST_MULTIARCH}/gir-1.0')
        os.environ['GI_GIR_PATH'] = ':'.join(paths)

        paths = os.environ.get('GI_TYPELIB_PATH', '').split(':')
        paths = [p for p in paths if p]
        paths.append(f'/usr/lib/{DEB_HOST_MULTIARCH}/girepository-1.0')
        os.environ['GI_TYPELIB_PATH'] = ':'.join(paths)

        extra_argv = []

        if TOOL == 'g-ir-scanner':
            if not self.can_run():
                extra_argv.append('--use-binary-wrapper=' + self.find_qemu())

            extra_argv.append(f'--use-ldd-wrapper={GET_NEEDED}')

        argv = [TOOL_PATH] + extra_argv + sys.argv[1:]
        try:
            os.execvp(TOOL_PATH, argv)
        except OSError:
            print(f'{ME}: Unable to run: {argv}')
            raise


if __name__ == '__main__':
    CrossGirTool(sys.argv).exec()
