# Path: scripts/pkgs/constants.py
# def uniq(vals):
#     def cpu_count():
# def build_dir():
# def set_build_dir(x):
# def current_source():
# def set_current_source(x):
# def set_tdir(x):
# def mkdtemp(prefix=''):
# def putenv(**kw):
# ROOT = 'C:\\' if iswindows else '/'
# SW = ROOT + 'sw'
# SOURCES = ROOT + 'sources'
# PATCHES = ROOT + 'patches'
# SCRIPTS = ROOT + 'scripts'
# CALIBRE_DIR = ROOT + 'calibre'
# PREFIX = os.path.join(SW, 'sw')
# BIN = os.path.join(PREFIX, 'bin')
# PYTHON = os.path.join(PREFIX, 'private', 'python', 'python.exe') if iswindows else os.path.join(BIN, 'python')
#     CFLAGS = CPPFLAGS = LIBDIR = LDFLAGS = ''
#     CFLAGS = worker_env['CFLAGS'] = '-I' + os.path.join(PREFIX, 'include')
#     CPPFLAGS = worker_env['CPPFLAGS'] = '-I' + os.path.join(PREFIX, 'include')
#     LIBDIR = os.path.join(PREFIX, 'lib')
#     LDFLAGS = worker_env['LDFLAGS'] = '-L{0} -Wl,-rpath-link,{0}'.format(LIBDIR)
#     LDFLAGS = worker_env['LDFLAGS'] = '-headerpad_max_install_names -L{}'.format(LIBDIR)
# MAKEOPTS = '-j%d' % cpu_count()
# PKG_CONFIG_PATH = worker_env['PKG_CONFIG_PATH'] = os.path.join(PREFIX, 'lib', 'pkgconfig')
# CMAKE = os.path.join(PREFIX, 'bin', 'cmake') if isosx else 'cmake'
# QT_PREFIX = os.path.join(PREFIX, 'qt')
# QT_DLLS = ['Qt5' + x for x in (
#     'Core', 'Gui', 'Network', 'PrintSupport', 'Positioning', 'Sensors', 'Sql',
#     'Svg', 'WebKit', 'WebKitWidgets', 'Widgets', 'Multimedia', 'OpenGL',
#     'MultimediaWidgets', 'Xml',  # 'XmlPatterns',
# )]
# QT_PLUGINS = [
#     'imageformats', 'iconengines', 'mediaservice', 'platforms',
#     'playlistformats', 'sqldrivers',
#     # 'audio', 'printsupport', 'bearer', 'position',
# ]
# PYQT_MODULES = ('Qt', 'QtCore', 'QtGui', 'QtNetwork',  # 'QtMultimedia', 'QtMultimediaWidgets',
#                 'QtPrintSupport', 'QtSensors', 'QtSvg', 'QtWebKit', 'QtWebKitWidgets', 'QtWidgets')
# CODESIGN_KEYCHAIN = '/Users/kovid/codesign.keychain'
#     class SYSTEM_INFO(ctypes.Structure):


from contextlib import contextmanager
from .constants import (
    build_dir, current_source, mkdtemp, PATCHES, PYTHON, MAKEOPTS, LIBDIR, SW,
    worker_env, islinux, PREFIX, iswindows, isosx
)
        from .constants import cygwin_paths
    from ctypes import wintypes
import time
import os
import shlex
import pipes
import subprocess
import sys
import errno
import glob
import shutil
import zipfile
import stat
    import ctypes
    import msvcrt
    old_mode = flipwritable(p)
    subprocess.check_call(cmd)
    if old_mode is not None:
        flipwritable(p, old_mode)


def is_macho_binary(p):
    try:
        with open(p, 'rb') as f:
            return f.read(4) in (b'\xcf\xfa\xed\xfe', b'\xfe\xed\xfa\xcf')
    except EnvironmentError as err:
        if err.errno == errno.ENOENT:
            return False
        raise


def fix_install_names(m, output_dir):
    dylibs = set()
    mfunc = getattr(m, 'install_name_change_predicate', lambda p: False)
    mcfunc = getattr(m, 'install_name_change', lambda old_name, is_dep: old_name)
    for dirpath, dirnames, filenames in os.walk(output_dir):
        for f in filenames:
            p = os.path.abspath(os.path.realpath(os.path.join(dirpath, f)))
            if p not in dylibs and os.path.exists(p):
                if p.endswith('.dylib') or ('bin' in p.split('/') and is_macho_binary(p)) or (mfunc(p) and is_macho_binary(p)):
                    dylibs.add(p)
    for p in dylibs:
        changes = []
        install_name, deps = read_lib_names(p)
        if install_name:

# Path: scripts/pkgs/constants.py
# def uniq(vals):
#     def cpu_count():
# def build_dir():
# def set_build_dir(x):
# def current_source():
# def set_current_source(x):
# def set_tdir(x):
# def mkdtemp(prefix=''):
# def putenv(**kw):
# ROOT = 'C:\\' if iswindows else '/'
# SW = ROOT + 'sw'
# SOURCES = ROOT + 'sources'
# PATCHES = ROOT + 'patches'
# SCRIPTS = ROOT + 'scripts'
# CALIBRE_DIR = ROOT + 'calibre'
# PREFIX = os.path.join(SW, 'sw')
# BIN = os.path.join(PREFIX, 'bin')
# PYTHON = os.path.join(PREFIX, 'private', 'python', 'python.exe') if iswindows else os.path.join(BIN, 'python')
#     CFLAGS = CPPFLAGS = LIBDIR = LDFLAGS = ''
#     CFLAGS = worker_env['CFLAGS'] = '-I' + os.path.join(PREFIX, 'include')
#     CPPFLAGS = worker_env['CPPFLAGS'] = '-I' + os.path.join(PREFIX, 'include')
#     LIBDIR = os.path.join(PREFIX, 'lib')
#     LDFLAGS = worker_env['LDFLAGS'] = '-L{0} -Wl,-rpath-link,{0}'.format(LIBDIR)
#     LDFLAGS = worker_env['LDFLAGS'] = '-headerpad_max_install_names -L{}'.format(LIBDIR)
# MAKEOPTS = '-j%d' % cpu_count()
# PKG_CONFIG_PATH = worker_env['PKG_CONFIG_PATH'] = os.path.join(PREFIX, 'lib', 'pkgconfig')
# CMAKE = os.path.join(PREFIX, 'bin', 'cmake') if isosx else 'cmake'
# QT_PREFIX = os.path.join(PREFIX, 'qt')
# QT_DLLS = ['Qt5' + x for x in (
#     'Core', 'Gui', 'Network', 'PrintSupport', 'Positioning', 'Sensors', 'Sql',
#     'Svg', 'WebKit', 'WebKitWidgets', 'Widgets', 'Multimedia', 'OpenGL',
#     'MultimediaWidgets', 'Xml',  # 'XmlPatterns',
# )]
# QT_PLUGINS = [
#     'imageformats', 'iconengines', 'mediaservice', 'platforms',
#     'playlistformats', 'sqldrivers',
#     # 'audio', 'printsupport', 'bearer', 'position',
# ]
# PYQT_MODULES = ('Qt', 'QtCore', 'QtGui', 'QtNetwork',  # 'QtMultimedia', 'QtMultimediaWidgets',
#                 'QtPrintSupport', 'QtSensors', 'QtSvg', 'QtWebKit', 'QtWebKitWidgets', 'QtWidgets')
# CODESIGN_KEYCHAIN = '/Users/kovid/codesign.keychain'
#     class SYSTEM_INFO(ctypes.Structure):


# Path: scripts/pkgs/utils.py
from contextlib import contextmanager
from .constants import (
    build_dir, current_source, mkdtemp, PATCHES, PYTHON, MAKEOPTS, LIBDIR, SW,
    worker_env, islinux, PREFIX, iswindows, isosx
)
        from .constants import cygwin_paths
    from ctypes import wintypes
import time
import os
import shlex
import pipes
import subprocess
import sys
import errno
import glob
import shutil
import zipfile
import stat
    import ctypes
    import msvcrt

    old_mode = flipwritable(p)
    subprocess.check_call(cmd)
    if old_mode is not None:
        flipwritable(p, old_mode)


def is_macho_binary(p):
    try:
        with open(p, 'rb') as f:
            return f.read(4) in (b'\xcf\xfa\xed\xfe', b'\xfe\xed\xfa\xcf')
    except EnvironmentError as err:
        if err.errno == errno.ENOENT:
            return False
        raise


def fix_install_names(m, output_dir):
    dylibs = set()
    mfunc = getattr(m, 'install_name_change_predicate', lambda p: False)
    mcfunc = getattr(m, 'install_name_change', lambda old_name, is_dep: old_name)
    for dirpath, dirnames, filenames in os.walk(output_dir):
        for f in filenames:
            p = os.path.abspath(os.path.realpath(os.path.join(dirpath, f)))
            if p not in dylibs and os.path.exists(p):
                if p.endswith('.dylib') or ('bin' in p.split('/') and is_macho_binary(p)) or (mfunc(p) and is_macho_binary(p)):
                    dylibs.add(p)
    for p in dylibs:
        changes = []
        install_name, deps = read_lib_names(p)
        if install_name:

            nn = install_name.replace(output_dir, PREFIX)