198 lines
9.4 KiB
Python
198 lines
9.4 KiB
Python
"""Build native system installers from the LanUps publish payloads."""
|
|
|
|
import hashlib
|
|
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, ICON, ROOT, binaries, tar_bytes, windows_package
|
|
|
|
NATIVE = DEPLOY / 'native'
|
|
OUTPUT = Path(os.environ.get('LANUPS_INSTALLER_OUTPUT', ROOT / 'artifacts' / 'native-installers-optimized')).resolve()
|
|
|
|
|
|
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'):
|
|
tar_bytes(archive, './' + name, script(source / name), 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 / 'lanups-router_0.1.0-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_package(rid, stage):
|
|
source = DEPLOY / 'linux'
|
|
architecture = {'linux-x64': 'amd64', 'linux-arm64': 'arm64'}[rid]
|
|
control, data = stage / 'control.tar.gz', stage / 'data.tar.gz'
|
|
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/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)
|
|
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 = (
|
|
'Package: lanups\nVersion: 0.1.0-1\n' f'Architecture: {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_0.1.0-1_{architecture}.deb'
|
|
with path.open('wb') as output:
|
|
output.write(b'!<arch>\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()
|
|
data.unlink()
|
|
return path
|
|
|
|
|
|
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='1', CFBundleShortVersionString='0.1.0')
|
|
(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)], check=True)
|
|
return output
|
|
|
|
|
|
def main(targets):
|
|
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-'):
|
|
output = linux_package(rid, stage)
|
|
elif rid.startswith('osx-'):
|
|
output = mac_package(rid, stage, builder)
|
|
elif rid == 'win-x64':
|
|
stub = stage / 'setup.exe'
|
|
env = dict(os.environ, GOOS='windows', GOARCH='amd64', CGO_ENABLED='0')
|
|
subprocess.run(['go','build','-trimpath','-ldflags=-s -w','-o',str(stub),str(NATIVE/'windows/main.go')],cwd=ROOT,env=env,check=True)
|
|
payload = windows_package(rid, stage / 'windows-payload.zip')
|
|
output = OUTPUT / 'LanUps-Setup-win-x64.exe'
|
|
with output.open('wb') as stream:
|
|
for part in (stub,payload):
|
|
with part.open('rb') as file:
|
|
shutil.copyfileobj(file, stream)
|
|
if os.name == 'nt':
|
|
subprocess.run([str(output),'--verify'],check=True)
|
|
else:
|
|
raise ValueError(f'Unsupported target: {rid}')
|
|
packages.append(output)
|
|
print(output.name, flush=True)
|
|
archives = [path for path in OUTPUT.iterdir() if path.suffix in {'.exe', '.deb', '.pkg', '.ipk'}]
|
|
with (OUTPUT / 'SHA256SUMS').open('w', encoding='ascii', newline='\n') as sums:
|
|
for path in sorted(archives):
|
|
with path.open('rb') as stream:
|
|
sums.write(f"{hashlib.file_digest(stream, 'sha256').hexdigest()} {path.name}\n")
|
|
print(packages[0].name, flush=True)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main(sys.argv[1:])
|