"""Build native system installers from the LanUps publish payloads.""" import argparse import io import os from pathlib import Path import plistlib import re import shutil import struct import subprocess import sys import tarfile import tempfile sys.dont_write_bytecode = True from package import DEPLOY, DIST, ICON, PAYLOAD, ROOT, VERSION, binaries, tar_bytes, write_checksums NATIVE = DEPLOY / 'native' OUTPUT = DIST def script(path): return path.read_bytes().replace(b'\r\n', b'\n') def tar_parents(archive, name, known): parts = name.removeprefix('./').split('/')[:-1] for length in range(1, len(parts) + 1): path = './' + '/'.join(parts[:length]) if path not in known: directory = tarfile.TarInfo(path) directory.type = tarfile.DIRTYPE directory.mode = 0o755 archive.addfile(directory) known.add(path) def router_package(): source = DEPLOY / 'router' control, data = io.BytesIO(), io.BytesIO() with tarfile.open(fileobj=control, mode='w:gz') as archive: for name in ('control', 'postinst', 'prerm'): content = script(source / name) if name == 'control': content += f'Version: {VERSION}-1\n'.encode('ascii') tar_bytes(archive, './' + name, content, 0o644 if name == 'control' else 0o755) with tarfile.open(fileobj=data, mode='w:gz') as archive: directories = set() for source_name, name in { 'install.sh': './usr/lib/lanups-router/install.sh', 'lanups-policy': './usr/sbin/lanups-policy', 'lanups-fsd.init': './etc/init.d/lanups-fsd', 'lanups-router': './usr/sbin/lanups-router', 'lanups-hotplug': './etc/hotplug.d/usb/95-lanups-router', }.items(): tar_parents(archive, name, directories) tar_bytes(archive, name, script(source / source_name), 0o755) path = OUTPUT / f'lanups-router_{VERSION}-1_all.ipk' with tarfile.open(path, 'w:gz') as archive: for name, value in (('debian-binary', b'2.0\n'), ('control.tar.gz', control.getvalue()), ('data.tar.gz', data.getvalue())): tar_bytes(archive, './' + name, value, 0o644) return path def write_ar_member(output, name, data): size = len(data) if isinstance(data, bytes) else data.stat().st_size output.write(f'{name + "/":16s}{0:<12d}{0:<6d}{0:<6d}{"100644":8s}{size:<10d}`\n'.encode('ascii')) if isinstance(data, bytes): output.write(data) else: with data.open('rb') as stream: shutil.copyfileobj(stream, output) if size % 2: output.write(b'\n') def linux_payload(rid, data): source = DEPLOY / 'linux' libc_version = (0, 0, 0) with tarfile.open(data, 'w:gz', compresslevel=5) as archive: directories = set() for kind in ('Agent', 'Desktop'): for path, name, executable in binaries(rid, kind): if executable or path.suffix == '.so': contents = path.read_bytes() if contents.startswith(b'\x7fELF'): for major, minor, patch in re.findall(rb'GLIBC_(\d+)\.(\d+)(?:\.(\d+))?\x00', contents): libc_version = max(libc_version, (int(major), int(minor), int(patch or b'0'))) item = tarfile.TarInfo(f'./opt/lanups/{kind.lower()}/{name}') tar_parents(archive, item.name, directories) item.size = path.stat().st_size item.mode = 0o755 if executable else 0o644 with path.open('rb') as stream: archive.addfile(item, stream) launcher = script(source / 'lanups-desktop.desktop') + b'Icon=lanups\n' for name, content, mode in ( ('./lib/systemd/system/lanups-agent.service', script(source / 'lanups-agent.service'), 0o644), ('./etc/xdg/autostart/lanups-desktop.desktop', launcher.replace(b'/opt/lanups/desktop/LanUps.Desktop --tray', b'/usr/lib/lanups/start-desktop'), 0o644), ('./usr/lib/lanups/start-desktop', script(source/'start-desktop'), 0o755), ('./usr/lib/lanups/configure-agent', script(source/'configure-agent'), 0o755), ('./usr/share/applications/lanups-desktop.desktop', launcher.replace(b' --tray', b''), 0o644), ('./usr/share/icons/hicolor/256x256/apps/lanups.png', ICON.read_bytes(), 0o644), ): tar_parents(archive, name, directories) tar_bytes(archive, name, content, mode) return libc_version def linux_deb(rid, stage, data, libc_version): source = DEPLOY / 'linux' architecture = {'linux-x64': 'amd64', 'linux-arm64': 'arm64'}[rid] control = stage / 'control.tar.gz' libc = 'libc6' if libc_version[0]: version = '.'.join(str(part) for part in (libc_version if libc_version[2] else libc_version[:2])) libc = f'libc6 (>= {version})' metadata = ( f'Package: lanups\nVersion: {VERSION}-1\nArchitecture: {architecture}\n' 'Maintainer: LanUps Project\nSection: utils\nPriority: optional\n' f'Depends: adduser, passwd, init-system-helpers, {libc}, libgcc-s1, libstdc++6, libssl3 | libssl3t64, libx11-6, libx11-xcb1, libxcb1, libxext6, libxi6, libxrandr2, libice6, libsm6, libfontconfig1, libgl1, libicu72 | libicu74 | libicu76 | libicu77 | libicu78\n' 'Description: LAN UPS Agent and desktop monitor\n' ) with tarfile.open(control, 'w:gz') as archive: tar_bytes(archive, './control', metadata.encode(), 0o644) for name in ('postinst', 'prerm', 'postrm'): tar_bytes(archive, './'+name, script(source / name), 0o755) path = OUTPUT / f'lanups_{VERSION}-1_{architecture}.deb' with path.open('wb') as output: output.write(b'!\n') for name, payload in (('debian-binary', b'2.0\n'), ('control.tar.gz', control), ('data.tar.gz', data)): write_ar_member(output, name, payload) control.unlink() return path def linux_rpm(rid, data): compiler = shutil.which('rpmbuild') if not compiler: raise RuntimeError('Install rpmbuild on the Linux packaging host to build RPM packages.') architecture = {'linux-x64': 'x86_64', 'linux-arm64': 'aarch64'}[rid] with tempfile.TemporaryDirectory(prefix='lanups-rpm-') as root: top = Path(root) sources = top / 'SOURCES' sources.mkdir() shutil.copyfile(data, sources / 'lanups-payload.tar.gz') subprocess.run([compiler, '-bb', '--target', architecture, '--define', f'_topdir {top}', '--define', f'lanups_version {VERSION}', str(DEPLOY / 'linux' / 'lanups.spec')], check=True) name = f'lanups-{VERSION}-1.{architecture}.rpm' return Path(shutil.copyfile(top / 'RPMS' / architecture / name, OUTPUT / name)) def mac_package(rid, stage, builder): source = DEPLOY / 'macos' payload = stage / rid for kind in ('Agent','Desktop'): prefix = 'usr/local/libexec/lanups/agent' if kind == 'Agent' else 'Applications/LanUps.app/Contents/MacOS' for path, name, executable in binaries(rid, kind): destination = payload / prefix / name destination.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(path, destination) bundle = payload / 'Applications/LanUps.app/Contents' (bundle / 'Resources').mkdir() plist = dict(CFBundleExecutable='LanUps.Desktop', CFBundleIdentifier='local.lanups.desktop', CFBundleName='LanUps', CFBundleDisplayName='局域网 UPS', CFBundlePackageType='APPL', CFBundleIconFile='ups.icns', CFBundleVersion=VERSION, CFBundleShortVersionString=VERSION) (bundle / 'Info.plist').write_bytes(plistlib.dumps(plist)) icon = ICON.read_bytes() (bundle / 'Resources/ups.icns').write_bytes(b'icns' + struct.pack('>I', len(icon)+16) + b'ic08' + struct.pack('>I', len(icon)+8) + icon) for path, location in (('local.lanups.agent.plist','Library/LaunchDaemons'), ('local.lanups.desktop.plist','usr/local/libexec/lanups')): target = payload / location / path target.parent.mkdir(parents=True, exist_ok=True) target.write_bytes(script(source / path)) for name in ('preinstall', 'postinstall'): (stage / name).write_bytes(script(source / name)) output = OUTPUT / f'LanUps-{rid}.pkg' subprocess.run([str(builder), str(payload), str(stage/'preinstall'), str(stage/'postinstall'), 'arm64' if rid == 'osx-arm64' else 'x86_64', str(output), VERSION], check=True) return output def windows_package(rid): compiler = os.environ.get('LANUPS_ISCC') or shutil.which('ISCC.exe') if not compiler: for env in ('ProgramFiles(x86)', 'ProgramFiles', 'LOCALAPPDATA'): if root := os.environ.get(env): candidate = Path(root) / 'Inno Setup 6' / 'ISCC.exe' if candidate.is_file(): compiler = str(candidate) break if not compiler: raise RuntimeError('Install Inno Setup 6 on the Windows build host or set LANUPS_ISCC to ISCC.exe.') for kind in ('Agent', 'Desktop'): next(binaries(rid, kind)) languages = Path(compiler).parent / 'Languages' options = ['/DChineseMessages=1'] if (languages / 'ChineseSimplified.isl').is_file() else [] subprocess.run([compiler, *options, f'/DAppVersion={VERSION}', f'/DPayloadDir={PAYLOAD / rid}', f'/O{OUTPUT}', f'/FLanUps-Setup-{rid}', str(DEPLOY / 'windows' / 'LanUps.iss')], check=True) return OUTPUT / f'LanUps-Setup-{rid}.exe' def main(targets, rpm=False): OUTPUT.mkdir(parents=True, exist_ok=True) packages = [router_package()] with tempfile.TemporaryDirectory(dir=OUTPUT.parent) as temp: stage = Path(temp) extension = '.exe' if os.name == 'nt' else '' builder = stage / ('macpack' + extension) if any(rid.startswith('osx-') for rid in targets): subprocess.run(['go','build','-mod=readonly','-trimpath','-o',str(builder),'.'],cwd=NATIVE/'macos',check=True) for rid in targets: if rid.startswith('linux-'): data = stage / f'{rid}.tar.gz' libc_version = linux_payload(rid, data) output = linux_deb(rid, stage, data, libc_version) if rpm: print(linux_rpm(rid, data).name, flush=True) elif rid.startswith('osx-'): output = mac_package(rid, stage, builder) elif rid == 'win-x64': output = windows_package(rid) else: raise ValueError(f'Unsupported target: {rid}') packages.append(output) print(output.name, flush=True) write_checksums() print(packages[0].name, flush=True) if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--rpm', action='store_true', help='Also build RPM installers for Linux targets') parser.add_argument('targets', nargs='*', help='Desktop targets. Omit to build only the router package.') args = parser.parse_args() main(args.targets, args.rpm)