#!/usr/bin/env python3 """Package Geminux flash images, pure-Linux MTK flasher, and TXT guide into a ZIP release.""" import argparse import datetime import hashlib import importlib.util import os import shutil import stat import subprocess import sys import tempfile import time import zipfile BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SCRIPTS_DIR = os.path.join(BASE_DIR, "scripts") SPARSE_MAGIC = b"\x3a\xff\x26\xed" FLASH_SCRIPTS = ( ("scripts/bootstrap-flash-deps.sh", True), ("scripts/extract-vendor-fw.py", True), ("scripts/geminux_accounts.py", False), ("scripts/geminux_gpt.py", True), ("scripts/geminux_luks.py", False), ) SKIP_VENDOR_DIRS = frozenset({"__pycache__"}) SKIP_VENDOR_FILES = frozenset({".DS_Store", ".state"}) SKIP_VENDOR_SUFFIXES = (".pyc", ".pyo") def _load_fw_mod(): fw_path = os.path.join(SCRIPTS_DIR, "extract-vendor-fw.py") spec = importlib.util.spec_from_file_location("extract_vendor_fw", fw_path) mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) return mod def _query_version_field(flag, fallback): ver_sh = os.path.join(SCRIPTS_DIR, "version.sh") if not os.path.isfile(ver_sh): return fallback res = subprocess.run([ver_sh, flag], capture_output=True, text=True, check=False) val = res.stdout.strip() return val if res.returncode == 0 and val else fallback def _query_git_commit_version(repo_dir=BASE_DIR): """Derive - from the latest git commit in repo_dir.""" try: res = subprocess.run( ["git", "-c", f"safe.directory={repo_dir}", "-C", repo_dir, "log", "-1", "--format=%ct %h"], capture_output=True, text=True, check=False, ) except OSError: return None if res.returncode != 0: return None parts = res.stdout.strip().split() if len(parts) != 2: return None try: commit_ts = int(parts[0]) except ValueError: return None short_sha = parts[1] commit_date = datetime.datetime.fromtimestamp( commit_ts, tz=datetime.timezone.utc ).strftime("%Y%m%d") return f"{commit_date}-{short_sha}" def resolve_release_version(version=None, repo_dir=BASE_DIR): """Resolve release version: explicit arg > GEMINUX_VERSION > git commit > version.sh fallback.""" if version and version.strip(): return version.strip() env_ver = os.environ.get("GEMINUX_VERSION", "").strip() if env_ver: return env_ver git_ver = _query_git_commit_version(repo_dir=repo_dir) if git_ver: return git_ver return _query_version_field("--print", "unknown") def sha256_file(path): """Compute streaming SHA-256 hex digest for a file.""" h = hashlib.sha256() with open(path, "rb") as f: while True: chunk = f.read(1048576) if not chunk: break h.update(chunk) return h.hexdigest() def copy_sparse_raw_image(src, dst): """Unsparse src if needed, otherwise copy sparsely into dst.""" with open(src, "rb") as f: is_sparse = f.read(4) == SPARSE_MAGIC if is_sparse: simg = shutil.which("simg2img") if not simg: raise RuntimeError("simg2img is required to unpack sparse geminux-rootfs.img") subprocess.run([simg, src, dst], check=True) return if shutil.which("cp"): subprocess.run(["cp", "--reflink=auto", "--sparse=always", src, dst], check=True) else: shutil.copyfile(src, dst) def _debugfs_ls_details(abs_img, internal_dir): """Return list of (name, mode_str) entries inside internal_dir of an ext4 image.""" res = subprocess.run( ["debugfs", "-R", f"ls -p /{internal_dir}", abs_img], capture_output=True, text=True, check=False, ) if res.returncode != 0: return [] out = [] for line in res.stdout.splitlines(): parts = line.split("/") if len(parts) >= 6: mode_str = parts[2] name = parts[5] if name and name not in (".", ".."): out.append((name, mode_str)) return out def sanitize_ext4_for_release(img_path, strip_firmware=False, strip_ssh_keys=True): """Remove SSH keys and/or proprietary MT6797 firmware blobs from a staged ext4 image.""" fw_mod = _load_fw_mod() abs_img = os.path.abspath(img_path) if not os.path.isfile(abs_img): raise FileNotFoundError(f"ext4 image not found: {abs_img}") if fw_mod._have_host_e2fs(): rm_paths = [] if strip_ssh_keys: if fw_mod._debugfs_path_exists(abs_img, "/root/.ssh/authorized_keys"): rm_paths.append("/root/.ssh/authorized_keys") for hname, hmode in _debugfs_ls_details(abs_img, "home"): if hmode.startswith("04"): ak = f"/home/{hname}/.ssh/authorized_keys" if fw_mod._debugfs_path_exists(abs_img, ak): rm_paths.append(ak) for ename, emode in _debugfs_ls_details(abs_img, "etc/ssh"): if not emode.startswith("04") and ename.startswith("ssh_host_"): rm_paths.append(f"/etc/ssh/{ename}") if strip_firmware: for fname, fmode in _debugfs_ls_details(abs_img, "lib/firmware/mediatek/mt6797"): if not fmode.startswith("04"): rm_paths.append(f"/lib/firmware/mediatek/mt6797/{fname}") if rm_paths: script = "\n".join(f"rm {p}" for p in rm_paths) + "\n" subprocess.run( ["debugfs", "-w", abs_img], input=script, text=True, check=True, stdout=subprocess.DEVNULL, ) subprocess.run(["e2fsck", "-fn", abs_img], check=True, stdout=subprocess.DEVNULL) return rm_paths # Docker fallback when host lacks e2fsprogs img_dir = os.path.dirname(abs_img) img_name = os.path.basename(abs_img) sf_flag = "1" if strip_firmware else "0" sk_flag = "1" if strip_ssh_keys else "0" docker_sh = f""" IMG="/img/{img_name}" RM_CMDS="" if [ "{sk_flag}" = "1" ]; then if debugfs -R "stat /root/.ssh/authorized_keys" "$IMG" 2>/dev/null | grep -q "Type:"; then RM_CMDS="$RM_CMDS rm /root/.ssh/authorized_keys" fi for u in $(debugfs -R "ls -p /home" "$IMG" 2>/dev/null | awk -F/ '$3 ~ /^04/ && $6 != "" && $6 != "." && $6 != ".." {{print $6}}'); do if debugfs -R "stat /home/$u/.ssh/authorized_keys" "$IMG" 2>/dev/null | grep -q "Type:"; then RM_CMDS="$RM_CMDS rm /home/$u/.ssh/authorized_keys" fi done for k in $(debugfs -R "ls -p /etc/ssh" "$IMG" 2>/dev/null | awk -F/ '$3 !~ /^04/ && $6 ~ /^ssh_host_/ {{print $6}}'); do RM_CMDS="$RM_CMDS rm /etc/ssh/$k" done fi if [ "{sf_flag}" = "1" ]; then for fw in $(debugfs -R "ls -p /lib/firmware/mediatek/mt6797" "$IMG" 2>/dev/null | awk -F/ '$3 !~ /^04/ && $6 != "" && $6 != "." && $6 != ".." {{print $6}}'); do RM_CMDS="$RM_CMDS rm /lib/firmware/mediatek/mt6797/$fw" done fi if [ -n "$RM_CMDS" ]; then printf '%s\n' "$RM_CMDS" | debugfs -w "$IMG" >/dev/null fi e2fsck -fn "$IMG" >/dev/null """ fw_mod._run_docker_e2fs(img_dir, [], docker_sh) return ["(sanitized via docker e2fsprogs)"] def _format_sanitize_summary(removed, include_firmware, keep_ssh_keys): """Format a clear rootfs sanitization summary distinguishing SSH keys vs firmware.""" if removed == ["(sanitized via docker e2fsprogs)"]: ssh_part = "SSH keys kept" if keep_ssh_keys else "SSH keys stripped" fw_part = "firmware kept" if include_firmware else "firmware stripped" return f"sanitized via docker e2fsprogs; {ssh_part}; {fw_part}; e2fsck clean" fw_removed = sum(1 for p in removed if p.startswith("/lib/firmware/")) key_removed = len(removed) - fw_removed ssh_part = "SSH keys kept" if keep_ssh_keys else f"stripped {key_removed} SSH key file(s)" fw_part = "firmware kept" if include_firmware else f"stripped {fw_removed} firmware file(s)" return f"{ssh_part}; {fw_part}; e2fsck clean" def render_flash_instructions(version, codename, build_date, top_dir, include_firmware=True): """Generate plain-text FLASH-INSTRUCTIONS.txt shipped inside the release ZIP.""" fw_mode = ( "INCLUDED (bundled in rootfs)" if include_firmware else "CLEAN / STRIPPED (auto-extracted from your PDA during flashing)" ) return f"""======================================================================== Geminux Linux for Planet Computers Gemini PDA (x27 Wi-Fi + 4G) Release: {version} ({codename}) Built: {build_date} Firmware: {fw_mode} ======================================================================== Archive Directory : {top_dir}/ 1. ARCHIVE CONTENTS ------------------- FLASH-INSTRUCTIONS.txt This guide SHA256SUMS.txt SHA-256 checksums for all disk images flash-mtk.sh / flash-mtk.py Pure-Linux MediaTek BROM/DA flasher images/boot-geminux.img Linux 7.3.5-geminux kernel + DTB + initramfs images/recovery-geminux.img USB NCM recovery shell image (172.16.42.1/24) images/geminux-rootfs.img Alpine Edge aarch64 desktop ext4 rootfs scripts/ Account, GPT, LUKS2, firmware & pip helpers vendor/mtkclient/ Vendored GPLv3 mtkclient + MT6797 DA binary 2. LINUX HOST PREREQUISITES --------------------------- Docker is NOT required to flash this release archive. Required on the Linux PC: - python3, python3-pip, libusb-1.0, and sudo (raw USB BROM/DA access) - e2fsprogs (debugfs, e2fsck) for account & firmware rootfs staging Optional: - cryptsetup Needed only if you choose --encrypt (LUKS2 disk encryption) - simg2img Needed only if extracting firmware from a sparse stock Android system.img (--extract-firmware --system-img) Note: On first run, ./flash-mtk.sh automatically installs its Python USB helpers (pyusb, pyserial, pycryptodome, colorama) locally into .flash-deps/ and temporarily pauses host ModemManager so /dev/ttyACM* is not interrupted. 3. SAFETY & HARDWARE PREPARATION -------------------------------- * Protected partitions (preloader, nvram, proinfo, lk, tee1, md1img, etc. in LBA 0..0x6FFFF) hold device calibration and baseband data. Geminux backs them up first and write-blocks them during normal flashing. * ALWAYS use the LEFT USB-C port on the Gemini PDA (closest to Esc), connected directly to the PC (avoid unpowered USB hubs). * Geminux claims all user-writable eMMC after 0x0E000000 (replacing Android system, cache, and userdata with boot, recovery, boot2, and ~58 GiB linux). 4. FLASHING STEPS ----------------- Extract this ZIP and change into {top_dir}/: unzip {top_dir}.zip cd {top_dir} Step A - Verify image checksums: sha256sum -c SHA256SUMS.txt Step B - Optional: backup factory partitions only (without modifying eMMC): # Keep Gemini powered off and unplugged, start the command, then plug into # the LEFT USB-C port: ./flash-mtk.sh --only-backup Step C - Full Geminux installation: # Interactive (prompts for username, passwords, and optional LUKS2 before # waiting for USB; automatically backs up factory partitions, extracts MT6797 # Wi-Fi/BT/SPM blobs from stock Android 'system', injects them into the # staged rootfs, repartitions eMMC, verifies readbacks, and reboots): ./flash-mtk.sh --flash-full # Example with explicit username, prompted passwords, and LUKS2 encryption: ./flash-mtk.sh --flash-full --username alice --ask-user-password \\ --ask-root-password --encrypt # Non-interactive with image defaults (unencrypted, user / geminux): ./flash-mtk.sh --flash-full --use-default-credentials # Already flashed Linux previously (no stock Android system partition left)? # Extract blobs once from your stock Android system.img beforehand: ./flash-mtk.sh --extract-firmware --system-img /path/to/stock-system.img ./flash-mtk.sh --flash-full 5. OTHER FLASHER COMMANDS ------------------------- # Re-flash kernel + recovery slots only (preserves GPT and linux rootfs): ./flash-mtk.sh --flash-kernel-only # Update only the linux rootfs partition: ./flash-mtk.sh --flash-rootfs-only --username alice --ask-user-password # Restore an earlier MediaTek partition backup (keep backup/ safe!): ./flash-mtk.sh --restore-backup backup/ 6. FIRST BOOT & QUICK REFERENCE ------------------------------- * After flashing finishes, unplug USB-C if needed and hold Esc to boot. * If booted on USB power, charging pauses briefly (~15 s) while VSYS stays powered so the fuel gauge reads true open-circuit battery voltage. * With --encrypt, unlock at the console prompt using the Gemini keyboard. * First boot automatically expands ext4 across the ~58 GiB linux partition. * Default login (unless customized): user / geminux (default theme: Anodized, default wallpaper: /usr/share/geminux/wallpapers/geminux-dark.png). * Rescue SSH: plug USB-C into a Linux host -> USB NCM usb0 at 172.16.42.1. Essential shortcuts (Fn+Alt = Mod4): Mod4 + Space App launcher Mod4 + t Themes & Wallpaper Mod4 + Return st terminal Mod4 + n Network, eSIM & DNS Mod4 + c Control Center Fn + F Airplane Mode Mod4 + Shift + l Lock screen Mod4 + Shift+c Close window 7. TROUBLESHOOTING ------------------ * Device boots Android/screen instead of flashing: Unplug USB-C, power off completely, run ./flash-mtk.sh first, then plug into the LEFT USB-C port. * Device hung before connecting: Hold Esc + side Power for ~12 s while plugged into the LEFT USB-C port to force hardware reset into BROM/Preloader. * Missing debugfs/e2fsck or cryptsetup: Install e2fsprogs (and cryptsetup if using --encrypt) from your Linux distribution's package manager. """ def _set_zipinfo_compress_level(zinfo, compress_level): level = None if compress_level == 0 else compress_level if hasattr(zinfo, "compress_level"): zinfo.compress_level = level elif hasattr(zinfo, "_compresslevel"): zinfo._compresslevel = level def _write_zip_entry(zf, src_path, arcname, is_exec, compress_level): st = os.stat(src_path) dt = time.localtime(st.st_mtime)[:6] if dt[0] < 1980: dt = (1980, 1, 1, 0, 0, 0) zinfo = zipfile.ZipInfo(arcname, date_time=dt) zinfo.compress_type = zipfile.ZIP_STORED if compress_level == 0 else zipfile.ZIP_DEFLATED _set_zipinfo_compress_level(zinfo, compress_level) zinfo.create_system = 3 mode = stat.S_IFREG | (0o755 if is_exec else 0o644) zinfo.external_attr = (mode & 0xFFFF) << 16 zinfo.file_size = st.st_size force64 = st.st_size >= 0xF0000000 with open(src_path, "rb") as sf, zf.open(zinfo, "w", force_zip64=force64) as df: shutil.copyfileobj(sf, df, length=4 * 1024 * 1024) def _write_zip_bytes(zf, raw_bytes, arcname, is_exec, compress_level): dt = time.gmtime()[:6] zinfo = zipfile.ZipInfo(arcname, date_time=dt) zinfo.compress_type = zipfile.ZIP_STORED if compress_level == 0 else zipfile.ZIP_DEFLATED _set_zipinfo_compress_level(zinfo, compress_level) zinfo.create_system = 3 mode = stat.S_IFREG | (0o755 if is_exec else 0o644) zinfo.external_attr = (mode & 0xFFFF) << 16 zinfo.file_size = len(raw_bytes) with zf.open(zinfo, "w") as df: df.write(raw_bytes) def _collect_vendor_entries(): vendor_root = os.path.join(BASE_DIR, "vendor", "mtkclient") if not os.path.isdir(vendor_root): raise FileNotFoundError(f"Missing vendored mtkclient directory: {vendor_root}") entries = [] for root, dirs, files in os.walk(vendor_root): dirs[:] = sorted(d for d in dirs if d not in SKIP_VENDOR_DIRS) for fn in sorted(files): if fn in SKIP_VENDOR_FILES or fn.endswith(SKIP_VENDOR_SUFFIXES): continue src = os.path.join(root, fn) if not os.path.isfile(src) or os.path.islink(src): continue rel = os.path.relpath(src, BASE_DIR).replace(os.sep, "/") is_exec = bool(os.stat(src).st_mode & 0o111) entries.append((src, rel, is_exec)) return entries def package_release_zip( images_dir, output_zip=None, version=None, codename=None, include_firmware=True, keep_ssh_keys=False, compress_level=9, verify=True, ): """Create a redistributable Geminux release ZIP archive with TXT flashing guide.""" ver = resolve_release_version(version) cname = codename or _query_version_field("--print-codename", "helio") top_dir = f"geminux-{ver}-{cname}-gemini-x27" if not output_zip: output_zip = os.path.join(BASE_DIR, "releases", f"{top_dir}.zip") abs_images = os.path.abspath(images_dir) abs_out = os.path.abspath(output_zip) out_dir = os.path.dirname(abs_out) or "." os.makedirs(out_dir, exist_ok=True) boot_img = os.path.join(abs_images, "boot-geminux.img") rec_img = os.path.join(abs_images, "recovery-geminux.img") root_img = os.path.join(abs_images, "geminux-rootfs.img") for req in (boot_img, rec_img, root_img): if not os.path.isfile(req): raise FileNotFoundError(f"Required build artifact not found: {req}") for top_tool in ("flash-mtk.sh", "flash-mtk.py"): if not os.path.isfile(os.path.join(BASE_DIR, top_tool)): raise FileNotFoundError(f"Missing flasher file: {top_tool}") with tempfile.TemporaryDirectory(dir=out_dir, prefix=".geminux-pkg-") as tmp: staged_root = os.path.join(tmp, "geminux-rootfs.img") print(f"[*] Staging rootfs image for release packaging ({root_img})...") copy_sparse_raw_image(root_img, staged_root) removed = sanitize_ext4_for_release( staged_root, strip_firmware=not include_firmware, strip_ssh_keys=not keep_ssh_keys, ) summary = _format_sanitize_summary(removed, include_firmware, keep_ssh_keys) print(f"[+] Sanitized staged ext4 rootfs ({summary}).") sums_lines = [ f"{sha256_file(boot_img)} images/boot-geminux.img", f"{sha256_file(staged_root)} images/geminux-rootfs.img", f"{sha256_file(rec_img)} images/recovery-geminux.img", ] sums_bytes = ("\n".join(sums_lines) + "\n").encode("utf-8") build_date = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d %H:%M UTC") guide_text = render_flash_instructions( ver, cname, build_date, top_dir, include_firmware=include_firmware ).encode("utf-8") tmp_zip = abs_out + ".tmp" if os.path.exists(tmp_zip): os.unlink(tmp_zip) print(f"[*] Writing ZIP archive -> {abs_out} (deflate level {compress_level})...") try: with zipfile.ZipFile( tmp_zip, "w", compression=zipfile.ZIP_STORED if compress_level == 0 else zipfile.ZIP_DEFLATED, compresslevel=compress_level, allowZip64=True, ) as zf: _write_zip_bytes(zf, guide_text, f"{top_dir}/FLASH-INSTRUCTIONS.txt", False, compress_level) _write_zip_bytes(zf, sums_bytes, f"{top_dir}/SHA256SUMS.txt", False, compress_level) _write_zip_entry(zf, os.path.join(BASE_DIR, "flash-mtk.sh"), f"{top_dir}/flash-mtk.sh", True, compress_level) _write_zip_entry(zf, os.path.join(BASE_DIR, "flash-mtk.py"), f"{top_dir}/flash-mtk.py", True, compress_level) for rel_script, is_exec in FLASH_SCRIPTS: src_s = os.path.join(BASE_DIR, rel_script) if not os.path.isfile(src_s): raise FileNotFoundError(f"Missing flasher helper script: {src_s}") _write_zip_entry(zf, src_s, f"{top_dir}/{rel_script}", is_exec, compress_level) for src_v, rel_v, is_exec in _collect_vendor_entries(): _write_zip_entry(zf, src_v, f"{top_dir}/{rel_v}", is_exec, compress_level) _write_zip_entry(zf, boot_img, f"{top_dir}/images/boot-geminux.img", False, compress_level) _write_zip_entry(zf, rec_img, f"{top_dir}/images/recovery-geminux.img", False, compress_level) _write_zip_entry(zf, staged_root, f"{top_dir}/images/geminux-rootfs.img", False, compress_level) if verify: print("[*] Verifying ZIP CRC32 integrity...") with zipfile.ZipFile(tmp_zip, "r") as zf: bad = zf.testzip() if bad is not None: raise RuntimeError(f"ZIP integrity verification failed at member: {bad}") os.replace(tmp_zip, abs_out) finally: if os.path.exists(tmp_zip): try: os.unlink(tmp_zip) except OSError: pass zip_sha = sha256_file(abs_out) sha_path = abs_out + ".sha256" with open(sha_path, "w", encoding="utf-8") as sf: sf.write(f"{zip_sha} {os.path.basename(abs_out)}\n") zip_mb = os.path.getsize(abs_out) / (1024.0 * 1024.0) print(f"[+] Packaged release ZIP: {abs_out} ({zip_mb:.1f} MiB)") print(f"[+] ZIP SHA-256: {zip_sha} ({sha_path})") return abs_out, sha_path def build_arg_parser(): p = argparse.ArgumentParser( description="Package Geminux images, pure-Linux MTK flasher, and TXT guide into a ZIP release." ) p.add_argument("-o", "--output", help="Output ZIP file path (default: releases/geminux---gemini-x27.zip)") p.add_argument("--images-dir", default=os.path.join(BASE_DIR, "images"), help="Directory containing boot-geminux.img, recovery-geminux.img, geminux-rootfs.img") p.add_argument("--version", help="Override Geminux release version string (default: recent git commit -, or GEMINUX_VERSION)") p.add_argument("--codename", help="Override Geminux codename") p.add_argument("--include-firmware", dest="include_firmware", action="store_true", default=True, help="Keep /lib/firmware/mediatek/mt6797 blobs inside packaged rootfs (default)") p.add_argument("--strip-firmware", dest="include_firmware", action="store_false", help="Strip /lib/firmware/mediatek/mt6797 blobs for clean redistribution") p.add_argument("--keep-ssh-keys", action="store_true", help="Keep SSH authorized_keys and ssh_host_* keys in packaged rootfs") p.add_argument("--compress-level", type=int, default=9, choices=range(0, 10), metavar="0..9", help="ZIP deflate compression level (default: 9)") p.add_argument("--no-verify", action="store_true", help="Skip ZIP CRC verification pass") return p def main(): args = build_arg_parser().parse_args() package_release_zip( images_dir=args.images_dir, output_zip=args.output, version=args.version, codename=args.codename, include_firmware=args.include_firmware, keep_ssh_keys=args.keep_ssh_keys, compress_level=args.compress_level, verify=not args.no_verify, ) return 0 if __name__ == "__main__": sys.exit(main())