Asukaa02 commited on
Commit
e415a9e
·
verified ·
1 Parent(s): 84d3747

Cubic for Colab - no-GUI custom Ubuntu ISO creator (initial release)

Browse files
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Cubic for Colab contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
README.md ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ tags:
4
+ - ubuntu
5
+ - iso
6
+ - google-colab
7
+ - cubic
8
+ - linux
9
+ - squashfs
10
+ - xorriso
11
+ - remaster
12
+ - no-gui
13
+ ---
14
+
15
+ # Cubic for Colab — custom Ubuntu ISO creator, no GUI
16
+
17
+ A headless, notebook-native re-implementation of the classic **Cubic (Custom Ubuntu ISO Creator)**
18
+ workflow, built for **Google Colab**. No desktop, no VNC, no windows — open the notebook, edit one
19
+ CONFIG cell, run everything top to bottom, and collect a bootable custom ISO from Google Drive.
20
+
21
+ [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/#file=https://huggingface.co/Asukaa02/cubic-colab/resolve/main/cubic_colab.ipynb)
22
+
23
+ ## Pipeline
24
+
25
+ ```
26
+ source ISO ──► xorriso extract ──► unsquashfs ──► chroot customise ──► mksquashfs ──► xorriso rebuild ──► Drive / download
27
+ (no loop-mount!) (live rootfs) (apt · PPAs · files) (repack) (boot layout kept)
28
+ ```
29
+
30
+ - **Extract** uses `xorriso -osirrox`, so nothing is ever loop-mounted — safe inside restricted containers.
31
+ - **Customise** runs a generated script inside a chroot of the unpacked live system (bind-mounts of
32
+ `/dev /proc /sys` are attempted best-effort and skipped gracefully when the runtime forbids them).
33
+ - **Rebuild** re-uses the exact boot equipment of the original ISO: xorriso's own
34
+ `report_el_torito as_mkisofs` output is transformed into a fresh build command, so BIOS (grub2 MBR +
35
+ El Torito) and UEFI (GPT appended ESP) boot paths survive repacking. Cell 7 prints the new ISO's
36
+ boot report next to the original's and verifies the ESP content byte-for-byte.
37
+ - **Deliver** copies the ISO plus a `.sha256` sidecar to `Drive â–¸ MyDrive â–¸ CubicColab`, with an
38
+ optional browser-download switch.
39
+
40
+ ## What you can customise
41
+
42
+ | Option | Effect |
43
+ |---|---|
44
+ | `APT_INSTALL` / `APT_PURGE` | add or remove apt packages in the live system |
45
+ | `PPA_REPOS` | add Launchpad PPAs (via `add-apt-repository`) |
46
+ | `DEB_URLS` | standalone `.deb` files, installed with `dpkg -i` |
47
+ | `ROOTFS_FILES` | drop files anywhere in the rootfs (wallpapers, configs, scripts) |
48
+ | `RUN_IN_CHROOT` | extra shell one-liners inside the chroot |
49
+ | `SET_HOSTNAME` | change the live + installed hostname |
50
+ | `KERNEL` | install another kernel (e.g. HWE) and optionally purge the old ones |
51
+ | `BOOT_MENU_EDITS` | rename GRUB boot-menu entries (text replacements in `boot/grub/grub.cfg`) |
52
+ | `ISO_FILES` | add extra files to the ISO tree itself |
53
+ | `SQUASH_COMPRESSION` | `auto` (detected from the original) or force `zstd` / `gzip` / `xz` |
54
+ | `OUTPUT` | Google Drive copy and/or browser download |
55
+
56
+ ## Quick start
57
+
58
+ 1. Open the notebook in Colab (badge above, or `File â–¸ Upload notebook` with `cubic_colab.ipynb`).
59
+ 2. Edit the `CONFIG` cell (source ISO URL, packages, files, boot-menu titles…).
60
+ 3. `Runtime â–¸ Run all`. The finished ISO lands in `WORK_ROOT/output/` and on your Google Drive.
61
+
62
+ A desktop ISO (~6 GB) needs ~30 GB of scratch disk and 40–90 minutes on the free CPU runtime;
63
+ smaller flavours (server, Lubuntu, Xubuntu) are faster and lighter. No GPU is used.
64
+
65
+ ## Command-line twin
66
+
67
+ `cubic_pipeline.py` is the exact same pipeline as a plain script for any root Linux box:
68
+
69
+ ```bash
70
+ sudo python3 cubic_pipeline.py
71
+ ```
72
+
73
+ Both files are generated from one source, so notebook and CLI never drift apart.
74
+
75
+ ## Requirements & notes
76
+
77
+ - Ubuntu/Debian system (Colab is preconfigured): `squashfs-tools`, `xorriso`, `grub-pc-bin`,
78
+ `mtools`, `libarchive-tools` — installed automatically by cell 2.
79
+ - Works with modern Ubuntu flavours (>= 20.04, casper + GRUB layout): desktop, server, Kubuntu,
80
+ Lubuntu, Xubuntu, MATE, Budgie, Studio, Kylin. Layered ISOs (e.g. server) are handled like Cubic:
81
+ the largest squashfs layer is edited.
82
+ - The source ISO can be a URL, a Files-panel upload, or a file from your Google Drive.
83
+ - SHA-256 verification against the official `SHA256SUMS` is built in.
84
+ - The chroot step always regenerates a clean `filesystem.manifest(-remove)` and `filesystem.size`,
85
+ and the ISO's `md5sum.txt` is rebuilt after repacking.
86
+
87
+ ## Validation
88
+
89
+ The pipeline was validated end-to-end on a synthetic ISO carrying the modern-Ubuntu hybrid boot
90
+ layout (grub2 MBR, GPT appended ESP, El Torito BIOS + EFI): the rebuilt image reproduces the
91
+ original boot report exactly — same ESP interval, same El Torito EFI pointer, ESP content
92
+ byte-identical to `efi.img`, patched `grub.cfg` intact, `md5sum.txt` consistent.
93
+
94
+ ## Troubleshooting
95
+
96
+ See the FAQ cell at the bottom of the notebook (re-run map, disk-space advice, SHA-256 recovery,
97
+ boot-menu string tips). Always smoke-test the ISO in a VM before flashing it.
98
+
99
+ ## Credits & license
100
+
101
+ Unofficial community tool — not affiliated with the Cubic project or Canonical. Inspired by
102
+ [Cubic](https://github.com/PJ-Singh-Net/Cubic). Code released under the MIT license (see `LICENSE`).
__pycache__/cubic_pipeline.cpython-312.pyc ADDED
Binary file (40.9 kB). View file
 
cubic_colab.ipynb ADDED
@@ -0,0 +1,886 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 5,
4
+ "metadata": {
5
+ "colab": {
6
+ "name": "Cubic for Colab \u2014 Custom Ubuntu ISO Creator (no GUI)",
7
+ "provenance": [],
8
+ "toc_visible": true
9
+ },
10
+ "kernelspec": {
11
+ "name": "python3",
12
+ "display_name": "Python 3"
13
+ },
14
+ "language_info": {
15
+ "name": "python"
16
+ }
17
+ },
18
+ "cells": [
19
+ {
20
+ "cell_type": "markdown",
21
+ "id": "6eb1b2ea2986",
22
+ "metadata": {},
23
+ "source": [
24
+ "# Cubic for Colab \u2014 build a custom Ubuntu ISO, no GUI needed\n",
25
+ "\n",
26
+ "A headless, notebook-native re-implementation of the classic **Cubic (Custom Ubuntu ISO Creator)**\n",
27
+ "workflow, designed for **Google Colab**: no desktop, no VNC, no window \u2014 just run the cells top to bottom.\n",
28
+ "\n",
29
+ "**Pipeline**\n",
30
+ "\n",
31
+ "```\n",
32
+ "source ISO \u2500\u2500\u25ba xorriso extract \u2500\u2500\u25ba unsquashfs \u2500\u2500\u25ba chroot customise \u2500\u2500\u25ba mksquashfs \u2500\u2500\u25ba xorriso rebuild \u2500\u2500\u25ba Drive / download\n",
33
+ " (no loop-mount!) (live rootfs) (apt \u00b7 PPAs \u00b7 files) (repack) (boot layout kept)\n",
34
+ "```\n",
35
+ "\n",
36
+ "**What you can customise**\n",
37
+ "\n",
38
+ "- apt packages, PPAs and standalone `.deb` files inside the live system\n",
39
+ "- files dropped anywhere in the rootfs (wallpapers, configs, scripts) and on the ISO itself\n",
40
+ "- the default kernel (e.g. install an HWE kernel and purge the old ones)\n",
41
+ "- hostname and the GRUB boot-menu titles\n",
42
+ "- squashfs compression (auto-detected from the original, or forced)\n",
43
+ "\n",
44
+ "**Before you start**\n",
45
+ "\n",
46
+ "| | desktop ISO (~6 GB) | server / small flavour ISO (~2.5\u20134 GB) |\n",
47
+ "|---|---|---|\n",
48
+ "| disk needed | ~30 GB | ~16 GB |\n",
49
+ "| wall time | 40\u201390 min | 25\u201360 min |\n",
50
+ "\n",
51
+ "Colab's CPU runtime is enough \u2014 **no GPU needed**. Free-tier Colab has ~100 GB of disk.\n",
52
+ "\n",
53
+ "> Unofficial community tool \u2014 not affiliated with the Cubic project or Canonical.\n",
54
+ "> Works with modern Ubuntu flavours (>= 20.04, casper + GRUB layout): desktop, server, Kubuntu,\n",
55
+ "> Lubuntu, Xubuntu, MATE, Budgie, Studio, Kylin."
56
+ ]
57
+ },
58
+ {
59
+ "cell_type": "code",
60
+ "id": "f6dcd8492307",
61
+ "metadata": {},
62
+ "execution_count": null,
63
+ "outputs": [],
64
+ "source": [
65
+ "# ==============================================================\n",
66
+ "# [1/8] CONFIGURATION \u2014 edit the values below, then\n",
67
+ "# Runtime \u25b8 Run all (or run the cells one by one)\n",
68
+ "# ==============================================================\n",
69
+ "CONFIG = {\n",
70
+ " # ---- source ISO --------------------------------------------------\n",
71
+ " # Any of:\n",
72
+ " # \"https://releases.ubuntu.com/24.04/ubuntu-24.04.5.1-desktop-amd64.iso\"\n",
73
+ " # \"/content/ubuntu-24.04.5.1-desktop-amd64.iso\" (uploaded via the Files panel)\n",
74
+ " # \"gdrive:ISOs/ubuntu-24.04.5.1-desktop-amd64.iso\" (a file in your Google Drive)\n",
75
+ " \"ISO_SOURCE\": \"https://releases.ubuntu.com/24.04/ubuntu-24.04.5.1-desktop-amd64.iso\",\n",
76
+ "\n",
77
+ " # Integrity check: a SHA256SUMS URL, a literal hash, or None to skip.\n",
78
+ " \"ISO_SHA256\": \"https://releases.ubuntu.com/24.04/SHA256SUMS\",\n",
79
+ "\n",
80
+ " # ---- workspace -----------------------------------------------------\n",
81
+ " \"WORK_ROOT\": \"/content/cubic-work\", # scratch space; needs ~2.5 x ISO size\n",
82
+ " \"KEEP_SOURCE_ISO\": True, # False = delete the downloaded .iso after extracting (saves disk)\n",
83
+ " \"FREE_ROOTFS_AFTER_REPACK\": True, # False = keep the unpacked rootfs for another edit round\n",
84
+ "\n",
85
+ " # ---- live-system customisations (inside the squashfs) ---------------\n",
86
+ " \"APT_INSTALL\": [\"vim\", \"htop\"], # packages to add, e.g. [\"vlc\", \"gimp\"]\n",
87
+ " \"APT_INSTALL_RECOMMENDS\": True, # also install recommended packages\n",
88
+ " \"APT_PURGE\": [], # packages to remove, e.g. [\"thunderbird\"]\n",
89
+ " \"PPA_REPOS\": [], # e.g. [\"ppa:mozillateam/ppa\"]\n",
90
+ " \"DEB_URLS\": [], # direct .deb URLs, installed with dpkg -i\n",
91
+ " \"ROOTFS_FILES\": [], # {\"src\": \"/content/me.png\", \"dst\": \"/usr/share/backgrounds/me.png\", \"mode\": \"0644\"}\n",
92
+ " \"RUN_IN_CHROOT\": [], # extra shell one-liners, e.g. [\"apt-get install -y git\"]\n",
93
+ " \"SET_HOSTNAME\": \"\", # e.g. \"my-ubuntu\"\n",
94
+ "\n",
95
+ " # Kernel handling:\n",
96
+ " # mode \"keep\" -> ship the kernel the ISO came with\n",
97
+ " # mode \"install\" -> apt-install the package below (e.g. a newer HWE kernel)\n",
98
+ " \"KERNEL\": {\"mode\": \"keep\", \"package\": \"linux-generic-hwe-24.04\", \"purge_old\": False},\n",
99
+ "\n",
100
+ " # ---- ISO-level customisations ---------------------------------------\n",
101
+ " \"BOOT_MENU_EDITS\": [], # [ [\"Try or Install Ubuntu\", \"Try or Install My Ubuntu\"], ... ]\n",
102
+ " \"ISO_FILES\": [], # {\"src\": \"/content/extra.cfg\", \"dst\": \"/extra.cfg\"} (paths on the ISO)\n",
103
+ "\n",
104
+ " # ---- repack & result --------------------------------------------------\n",
105
+ " \"SQUASH_COMPRESSION\": \"auto\", # auto | zstd | gzip | xz | e.g. \"zstd:5\"\n",
106
+ " \"OUTPUT_NAME\": \"custom-ubuntu.iso\",\n",
107
+ " \"OUTPUT\": {\"gdrive\": True, # copy the result to Drive > MyDrive > CubicColab\n",
108
+ " \"browser_download\": False} # also pop a browser download (for ISOs < ~2 GB)\n",
109
+ "}\n",
110
+ "\n",
111
+ "def _show_config(c=CONFIG):\n",
112
+ " print(f\" source ISO : {c['ISO_SOURCE']}\")\n",
113
+ " print(f\" sha256 check : {c['ISO_SHA256'] or 'skipped'}\")\n",
114
+ " print(f\" work dir : {c['WORK_ROOT']}\")\n",
115
+ " print(f\" apt install/purge : {c['APT_INSTALL']} / {c['APT_PURGE']}\")\n",
116
+ " print(f\" PPAs / deb URLs : {c['PPA_REPOS']} / {len(c['DEB_URLS'])} file(s)\")\n",
117
+ " print(f\" rootfs/iso files : {len(c['ROOTFS_FILES'])} / {len(c['ISO_FILES'])}\")\n",
118
+ " print(f\" kernel : {c['KERNEL']}\")\n",
119
+ " print(f\" hostname : {c['SET_HOSTNAME'] or 'unchanged'}\")\n",
120
+ " print(f\" boot-menu edits : {len(c['BOOT_MENU_EDITS'])}\")\n",
121
+ " print(f\" compression : {c['SQUASH_COMPRESSION']}\")\n",
122
+ " print(f\" output : {c['OUTPUT_NAME']} {c['OUTPUT']}\")\n",
123
+ "\n",
124
+ "_show_config()\n",
125
+ "print(\"\\nCONFIG loaded. Everything except ISO_SOURCE is optional.\")"
126
+ ]
127
+ },
128
+ {
129
+ "cell_type": "markdown",
130
+ "id": "c59d5bef1cba",
131
+ "metadata": {},
132
+ "source": [
133
+ "## How to configure (cell 1)\n",
134
+ "\n",
135
+ "Edit `CONFIG` \u2014 everything else is automatic. Common recipes:\n",
136
+ "\n",
137
+ "```python\n",
138
+ "# add packages, a PPA and a standalone .deb\n",
139
+ "CONFIG[\"APT_INSTALL\"] = [\"vim\", \"htop\", \"vlc\"]\n",
140
+ "CONFIG[\"PPA_REPOS\"] = [\"ppa:mozillateam/ppa\"]\n",
141
+ "CONFIG[\"DEB_URLS\"] = [\"https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb\"]\n",
142
+ "\n",
143
+ "# ship a wallpaper and a config file into the live system\n",
144
+ "CONFIG[\"ROOTFS_FILES\"] = [{\"src\": \"/content/wall.jpg\",\n",
145
+ " \"dst\": \"/usr/share/backgrounds/wall.jpg\", \"mode\": \"0644\"}]\n",
146
+ "\n",
147
+ "# rename the boot-menu entry (strings must appear in boot/grub/grub.cfg)\n",
148
+ "CONFIG[\"BOOT_MENU_EDITS\"] = [[\"Try or Install Ubuntu\", \"Try or Install My Ubuntu\"]]\n",
149
+ "\n",
150
+ "# newer kernel, drop the old ones\n",
151
+ "CONFIG[\"KERNEL\"] = {\"mode\": \"install\", \"package\": \"linux-generic-hwe-24.04\", \"purge_old\": True}\n",
152
+ "\n",
153
+ "# use an ISO you already have (Files panel upload or Google Drive)\n",
154
+ "CONFIG[\"ISO_SOURCE\"] = \"/content/ubuntu-24.04.5.1-desktop-amd64.iso\"\n",
155
+ "CONFIG[\"ISO_SHA256\"] = None\n",
156
+ "```\n",
157
+ "\n",
158
+ "Run the cells **in order**. If a cell fails, fix the cause (usually `CONFIG` or disk space) and\n",
159
+ "re-run that cell \u2014 each cell is idempotent and checks that earlier cells have run."
160
+ ]
161
+ },
162
+ {
163
+ "cell_type": "code",
164
+ "id": "80d8d7764edf",
165
+ "metadata": {},
166
+ "execution_count": null,
167
+ "outputs": [],
168
+ "source": [
169
+ "# ==============================================================\n",
170
+ "# [2/8] ENVIRONMENT SETUP \u2014 install tools, create the workspace\n",
171
+ "# ==============================================================\n",
172
+ "import os, sys, glob, re, json, shutil, subprocess, time, struct, hashlib\n",
173
+ "\n",
174
+ "IN_COLAB = False\n",
175
+ "try:\n",
176
+ " from google.colab import drive, files # noqa: F401\n",
177
+ " IN_COLAB = True\n",
178
+ "except Exception:\n",
179
+ " pass\n",
180
+ "\n",
181
+ "WORK = CONFIG[\"WORK_ROOT\"]\n",
182
+ "SRC_ISO = os.path.join(WORK, \"source.iso\")\n",
183
+ "ISO_TREE = os.path.join(WORK, \"iso-tree\")\n",
184
+ "SQUASH_DIR = os.path.join(WORK, \"rootfs-edit\")\n",
185
+ "OUT_DIR = os.path.join(WORK, \"output\")\n",
186
+ "META = os.path.join(WORK, \"build-meta.json\")\n",
187
+ "for _d in (WORK, ISO_TREE, SQUASH_DIR, OUT_DIR):\n",
188
+ " os.makedirs(_d, exist_ok=True)\n",
189
+ "\n",
190
+ "_T0 = time.monotonic()\n",
191
+ "def lap(label):\n",
192
+ " print(f\"[timer] {label}: {(time.monotonic() - _T0) / 60:.1f} min elapsed\")\n",
193
+ "\n",
194
+ "def disk_gb(path=\"/\"):\n",
195
+ " return shutil.disk_usage(path).free / 1e9\n",
196
+ "\n",
197
+ "def run(cmd, check=True, quiet=False):\n",
198
+ " \"\"\"Run a shell command, stream its output, abort the cell on failure.\"\"\"\n",
199
+ " if not quiet:\n",
200
+ " print(\"$ \" + cmd)\n",
201
+ " r = subprocess.run(cmd, shell=True)\n",
202
+ " if check and r.returncode != 0:\n",
203
+ " raise SystemExit(f\"\\n*** command failed (exit {r.returncode}). Fix it and re-run this cell. ***\")\n",
204
+ " return r.returncode\n",
205
+ "\n",
206
+ "def check_prereq(*names):\n",
207
+ " missing = [n for n in names if n not in globals()]\n",
208
+ " if missing:\n",
209
+ " raise SystemExit(f\"*** run the earlier cell(s) first \u2014 missing: {', '.join(missing)} ***\")\n",
210
+ "\n",
211
+ "def resolve_src(src, tag=\"file\"):\n",
212
+ " \"\"\"Local path or URL -> local path.\"\"\"\n",
213
+ " if src.startswith(\"http\"):\n",
214
+ " p = os.path.join(WORK, \"dl-\" + tag)\n",
215
+ " run(f\"wget -q -O '{p}' '{src}'\")\n",
216
+ " return p\n",
217
+ " if os.path.isfile(src):\n",
218
+ " return src\n",
219
+ " raise SystemExit(f\"*** source not found: {src} ***\")\n",
220
+ "\n",
221
+ "def read_pvd_volume_id(path):\n",
222
+ " \"\"\"Volume label straight from the ISO9660 primary volume descriptor.\"\"\"\n",
223
+ " with open(path, \"rb\") as f:\n",
224
+ " for off in (32768, 16 * 2048): # plain and partition_offset=16 layouts\n",
225
+ " f.seek(off)\n",
226
+ " pvd = f.read(2048)\n",
227
+ " if pvd[1:6] == b\"CD001\" and pvd[0:1] == b\"\\x01\":\n",
228
+ " return pvd[40:72].decode(\"ascii\", \"replace\").strip()\n",
229
+ " return \"UBUNTU_ISO\"\n",
230
+ "\n",
231
+ "def detect_boot_layout(path):\n",
232
+ " \"\"\"MBR/GPT facts we may need to reproduce the hybrid boot setup.\"\"\"\n",
233
+ " info = {\"partition_offset\": 0, \"gpt\": False, \"esp_bytes\": None, \"esp_first_lba\": None}\n",
234
+ " try:\n",
235
+ " with open(path, \"rb\") as f:\n",
236
+ " f.seek(446 + 8)\n",
237
+ " if struct.unpack(\"<I\", f.read(4))[0] * 512 == 16 * 2048:\n",
238
+ " info[\"partition_offset\"] = 16\n",
239
+ " f.seek(512)\n",
240
+ " hdr = f.read(512)\n",
241
+ " if hdr[:8] == b\"EFI PART\":\n",
242
+ " info[\"gpt\"] = True\n",
243
+ " n = struct.unpack_from(\"<I\", hdr, 80)[0]\n",
244
+ " esz = struct.unpack_from(\"<I\", hdr, 84)[0]\n",
245
+ " ent_lba = struct.unpack_from(\"<Q\", hdr, 72)[0]\n",
246
+ " f.seek(ent_lba * 512)\n",
247
+ " ents = f.read(min(n, 128) * esz)\n",
248
+ " if n >= 1 and struct.unpack_from(\"<Q\", ents, 32)[0] * 512 == 16 * 2048:\n",
249
+ " info[\"partition_offset\"] = 16\n",
250
+ " if n >= 2:\n",
251
+ " first = struct.unpack_from(\"<Q\", ents, esz + 32)[0]\n",
252
+ " last = struct.unpack_from(\"<Q\", ents, esz + 40)[0]\n",
253
+ " info[\"esp_first_lba\"] = first\n",
254
+ " info[\"esp_bytes\"] = (last - first + 1) * 512\n",
255
+ " except Exception as e:\n",
256
+ " print(\"boot-layout detection warning:\", e)\n",
257
+ " return info\n",
258
+ "\n",
259
+ "print(f\"Python {sys.version.split()[0]} | Colab: {IN_COLAB} | root: {os.geteuid() == 0}\")\n",
260
+ "print(f\"Disk: {disk_gb():.1f} GB free on /\")\n",
261
+ "if os.geteuid() != 0:\n",
262
+ " print(\"WARNING: not running as root \u2014 apt/chroot will fail. In Colab you are root by default.\")\n",
263
+ "if disk_gb() < 15:\n",
264
+ " print(\"WARNING: < 15 GB free. A desktop-ISO build wants ~30 GB; server/Lubuntu builds ~16 GB.\")\n",
265
+ "\n",
266
+ "if os.geteuid() == 0:\n",
267
+ " run(\"apt-get update -q\")\n",
268
+ " run(\"DEBIAN_FRONTEND=noninteractive apt-get install -y -q \"\n",
269
+ " \"squashfs-tools xorriso mtools libarchive-tools grub-pc-bin\")\n",
270
+ "else:\n",
271
+ " print(\"Not root: skipping apt \u2014 ensure squashfs-tools, xorriso and grub-pc-bin are installed.\")\n",
272
+ "print(\"Tools ready. Workspace:\", WORK)"
273
+ ]
274
+ },
275
+ {
276
+ "cell_type": "code",
277
+ "id": "0e10fd7071d9",
278
+ "metadata": {},
279
+ "execution_count": null,
280
+ "outputs": [],
281
+ "source": [
282
+ "# ==============================================================\n",
283
+ "# [3/8] GET THE SOURCE ISO \u2014 download / Google Drive / uploaded file\n",
284
+ "# ==============================================================\n",
285
+ "check_prereq(\"CONFIG\", \"SRC_ISO\", \"WORK\", \"run\")\n",
286
+ "\n",
287
+ "src = CONFIG[\"ISO_SOURCE\"]\n",
288
+ "DOWNLOADED = False\n",
289
+ "if src.startswith(\"http\"):\n",
290
+ " print(\"Downloading ISO (resumable \u2014 be patient)\u2026\")\n",
291
+ " run(f\"wget -c -q --show-progress -O '{SRC_ISO}' '{src}'\")\n",
292
+ " DOWNLOADED = True\n",
293
+ "elif src.startswith(\"gdrive:\"):\n",
294
+ " if not IN_COLAB:\n",
295
+ " raise SystemExit(\"*** gdrive: sources only work in Colab ***\")\n",
296
+ " from google.colab import drive\n",
297
+ " drive.mount(\"/content/drive\", force_remount=True)\n",
298
+ " gd = \"/content/drive/MyDrive/\" + src.split(\":\", 1)[1].lstrip(\"/\")\n",
299
+ " if not os.path.isfile(gd):\n",
300
+ " raise SystemExit(f\"*** not found in Google Drive: {gd} ***\")\n",
301
+ " print(\"Copying out of Drive\u2026\")\n",
302
+ " shutil.copy2(gd, SRC_ISO)\n",
303
+ "elif os.path.isfile(src):\n",
304
+ " SRC_ISO = src\n",
305
+ "else:\n",
306
+ " raise SystemExit(\"*** ISO_SOURCE not found. Upload the .iso via the Files panel (left sidebar) \"\n",
307
+ " \"and point CONFIG['ISO_SOURCE'] at it, or use a URL. ***\")\n",
308
+ "\n",
309
+ "print(f\"ISO ready: {SRC_ISO} ({os.path.getsize(SRC_ISO) / 1e9:.2f} GB)\")\n",
310
+ "\n",
311
+ "chk = CONFIG.get(\"ISO_SHA256\")\n",
312
+ "if chk:\n",
313
+ " h = hashlib.sha256()\n",
314
+ " with open(SRC_ISO, \"rb\") as f:\n",
315
+ " for chunk in iter(lambda: f.read(1 << 22), b\"\"):\n",
316
+ " h.update(chunk)\n",
317
+ " actual = h.hexdigest()\n",
318
+ " expected = None\n",
319
+ " if chk.startswith(\"http\"):\n",
320
+ " sums = os.path.join(WORK, \"SHA256SUMS\")\n",
321
+ " run(f\"wget -q -O '{sums}' '{chk}'\", check=False)\n",
322
+ " base = os.path.basename(SRC_ISO)\n",
323
+ " for line in open(sums, errors=\"ignore\"):\n",
324
+ " parts = line.split()\n",
325
+ " if len(parts) == 2 and parts[1].lstrip(\"*\") == base:\n",
326
+ " expected = parts[0].lower()\n",
327
+ " break\n",
328
+ " if expected is None:\n",
329
+ " print(\"WARNING: no entry for this file in SHA256SUMS \u2014 verification skipped\")\n",
330
+ " else:\n",
331
+ " expected = chk.strip().lower()\n",
332
+ " if expected:\n",
333
+ " if expected != actual:\n",
334
+ " raise SystemExit(\"*** SHA256 MISMATCH \u2014 the download is corrupt.\\n\"\n",
335
+ " f\" expected {expected}\\n actual {actual}\\n\"\n",
336
+ " f\" Delete {SRC_ISO} and re-run this cell. ***\")\n",
337
+ " print(\"SHA256 verified:\", actual)"
338
+ ]
339
+ },
340
+ {
341
+ "cell_type": "code",
342
+ "id": "bb1a1a46b4b8",
343
+ "metadata": {},
344
+ "execution_count": null,
345
+ "outputs": [],
346
+ "source": [
347
+ "# ==============================================================\n",
348
+ "# [4/8] EXTRACT \u2014 unpack the ISO and its live filesystem\n",
349
+ "# (pure file operations, nothing is mounted)\n",
350
+ "# ==============================================================\n",
351
+ "check_prereq(\"CONFIG\", \"SRC_ISO\", \"ISO_TREE\", \"SQUASH_DIR\", \"DOWNLOADED\", \"run\")\n",
352
+ "\n",
353
+ "if os.path.isdir(ISO_TREE):\n",
354
+ " subprocess.run(f\"chmod -R u+w '{ISO_TREE}' 2>/dev/null\", shell=True)\n",
355
+ " shutil.rmtree(ISO_TREE)\n",
356
+ "if os.path.isdir(SQUASH_DIR):\n",
357
+ " subprocess.run(f\"chmod -R u+w '{SQUASH_DIR}' 2>/dev/null\", shell=True)\n",
358
+ " shutil.rmtree(SQUASH_DIR)\n",
359
+ "\n",
360
+ "print(\"Extracting the ISO tree with xorriso (no loop-mount needed)\u2026\")\n",
361
+ "run(f\"xorriso -osirrox on -indev '{SRC_ISO}' -extract / '{ISO_TREE}'\")\n",
362
+ "run(f\"chmod -R u+w '{ISO_TREE}'\") # xorriso restores files read-only\n",
363
+ "lap(\"ISO tree extraction\")\n",
364
+ "\n",
365
+ "print(\"Looking for the casper squashfs\u2026\")\n",
366
+ "cands = sorted(glob.glob(f\"{ISO_TREE}/casper/*.squashfs\")\n",
367
+ " + glob.glob(f\"{ISO_TREE}/*/casper/*.squashfs\")\n",
368
+ " + glob.glob(f\"{ISO_TREE}/live/*.squashfs\"),\n",
369
+ " key=os.path.getsize)\n",
370
+ "if not cands:\n",
371
+ " raise SystemExit(\"*** no casper/live squashfs found \u2014 is this really an Ubuntu live ISO? ***\")\n",
372
+ "SQ_PATH = max(cands, key=os.path.getsize)\n",
373
+ "print(\"Found:\", \", \".join(os.path.basename(c) for c in cands), \"-> editing\", os.path.basename(SQ_PATH))\n",
374
+ "if len(cands) > 1:\n",
375
+ " print(\"NOTE: several squashfs layers present; only the largest one is edited (like Cubic does).\")\n",
376
+ "\n",
377
+ "_s = subprocess.run(f\"unsquashfs -s '{SQ_PATH}'\", shell=True, capture_output=True, text=True).stdout\n",
378
+ "_m = re.search(r\"Compression (\\w+)\", _s)\n",
379
+ "SQUASH_COMP = _m.group(1) if _m else \"zstd\"\n",
380
+ "print(\"Original squashfs compression:\", SQUASH_COMP)\n",
381
+ "\n",
382
+ "print(\"Unpacking the live filesystem (several minutes on first run)\u2026\")\n",
383
+ "run(f\"unsquashfs -d '{SQUASH_DIR}' '{SQ_PATH}'\")\n",
384
+ "lap(\"squashfs extraction\")\n",
385
+ "\n",
386
+ "# metadata for the rebuild step\n",
387
+ "_rep = subprocess.run(f\"xorriso -indev '{SRC_ISO}' -report_el_torito as_mkisofs\",\n",
388
+ " shell=True, capture_output=True, text=True)\n",
389
+ "json.dump({\n",
390
+ " \"volid\": read_pvd_volume_id(SRC_ISO),\n",
391
+ " \"report\": _rep.stdout,\n",
392
+ " \"comp\": SQUASH_COMP,\n",
393
+ " \"boot\": detect_boot_layout(SRC_ISO),\n",
394
+ " \"sq_name\": os.path.basename(SQ_PATH),\n",
395
+ "}, open(META, \"w\"))\n",
396
+ "_mf = f\"{ISO_TREE}/casper/filesystem.manifest\"\n",
397
+ "if os.path.isfile(_mf):\n",
398
+ " _om = os.path.join(WORK, \"orig.manifest\")\n",
399
+ " if os.path.exists(_om):\n",
400
+ " os.chmod(_om, 0o644) # copy2 preserves read-only modes\n",
401
+ " shutil.copy2(_mf, _om)\n",
402
+ " os.chmod(_om, 0o644)\n",
403
+ "\n",
404
+ "if (not CONFIG[\"KEEP_SOURCE_ISO\"]) and DOWNLOADED and os.path.exists(SRC_ISO):\n",
405
+ " os.remove(SRC_ISO)\n",
406
+ " print(\"Source ISO deleted to free disk (KEEP_SOURCE_ISO=False).\")\n",
407
+ "\n",
408
+ "print(f\"Disk now: {disk_gb():.1f} GB free\")"
409
+ ]
410
+ },
411
+ {
412
+ "cell_type": "code",
413
+ "id": "a14eb06a4cee",
414
+ "metadata": {},
415
+ "execution_count": null,
416
+ "outputs": [],
417
+ "source": [
418
+ "# ==============================================================\n",
419
+ "# [5/8] CUSTOMISE THE LIVE SYSTEM \u2014 apt, PPAs, files, kernel, chroot\n",
420
+ "# ==============================================================\n",
421
+ "check_prereq(\"CONFIG\", \"SQUASH_DIR\", \"WORK\", \"run\")\n",
422
+ "\n",
423
+ "def _safe(tok, pat, what):\n",
424
+ " if not re.match(pat, tok):\n",
425
+ " raise SystemExit(f\"*** invalid {what}: {tok!r} ***\")\n",
426
+ "\n",
427
+ "for _p in CONFIG[\"APT_INSTALL\"] + CONFIG[\"APT_PURGE\"]:\n",
428
+ " _safe(_p, r\"^[A-Za-z0-9._+:-]+$\", \"package name\")\n",
429
+ "for _p in CONFIG[\"PPA_REPOS\"]:\n",
430
+ " _safe(_p, r\"^(ppa:[A-Za-z0-9._/-]+|https?://\\S+)$\", \"PPA\")\n",
431
+ "_h = CONFIG.get(\"SET_HOSTNAME\", \"\")\n",
432
+ "if _h:\n",
433
+ " _safe(_h, r\"^[A-Za-z0-9][A-Za-z0-9.-]*$\", \"hostname\")\n",
434
+ "\n",
435
+ "did_any = bool(CONFIG[\"APT_INSTALL\"] or CONFIG[\"APT_PURGE\"] or CONFIG[\"PPA_REPOS\"]\n",
436
+ " or CONFIG[\"DEB_URLS\"] or CONFIG[\"ROOTFS_FILES\"] or CONFIG[\"RUN_IN_CHROOT\"]\n",
437
+ " or CONFIG.get(\"SET_HOSTNAME\")\n",
438
+ " or CONFIG[\"KERNEL\"].get(\"mode\") == \"install\" or CONFIG[\"KERNEL\"].get(\"purge_old\"))\n",
439
+ "\n",
440
+ "if not did_any:\n",
441
+ " print(\"No live-system customisations configured \u2014 skipping this step.\")\n",
442
+ "else:\n",
443
+ " # -- copy files into the rootfs / fetch .deb files --------------------\n",
444
+ " debdir = os.path.join(SQUASH_DIR, \"tmp/cubic-debs\")\n",
445
+ " os.makedirs(debdir, exist_ok=True)\n",
446
+ " for i, item in enumerate(CONFIG[\"ROOTFS_FILES\"]):\n",
447
+ " s = resolve_src(item[\"src\"], f\"rootfs{i}\")\n",
448
+ " dst = os.path.join(SQUASH_DIR, item[\"dst\"].lstrip(\"/\"))\n",
449
+ " os.makedirs(os.path.dirname(dst), exist_ok=True)\n",
450
+ " shutil.copy2(s, dst)\n",
451
+ " if item.get(\"mode\"):\n",
452
+ " os.chmod(dst, int(item[\"mode\"], 8))\n",
453
+ " print(\"rootfs file :\", item[\"dst\"])\n",
454
+ " for i, u in enumerate(CONFIG[\"DEB_URLS\"]):\n",
455
+ " run(f\"wget -q -O '{debdir}/extra{i}.deb' '{u}'\")\n",
456
+ "\n",
457
+ " # -- DNS for the chroot ------------------------------------------------\n",
458
+ " resolv = os.path.join(SQUASH_DIR, \"etc/resolv.conf\")\n",
459
+ " resolv_was_link = os.path.islink(resolv)\n",
460
+ " resolv_bak = resolv + \".cubicbak\"\n",
461
+ " if not resolv_was_link and os.path.isfile(resolv):\n",
462
+ " shutil.copy2(resolv, resolv_bak)\n",
463
+ " with open(resolv, \"w\") as f:\n",
464
+ " f.write(\"nameserver 8.8.8.8\\nnameserver 1.1.1.1\\n\")\n",
465
+ "\n",
466
+ " # -- bind /dev /proc /sys (best effort; apt works without them) --------\n",
467
+ " binds = []\n",
468
+ " for nm in (\"dev\", \"proc\", \"sys\"):\n",
469
+ " if subprocess.run(f\"mount --bind /{nm} '{SQUASH_DIR}/{nm}'\", shell=True).returncode == 0:\n",
470
+ " binds.append(f\"{SQUASH_DIR}/{nm}\")\n",
471
+ " if len(binds) < 3:\n",
472
+ " print(\"NOTE: /dev /proc /sys bind-mounts unavailable here \u2014 the chroot runs without them. \"\n",
473
+ " \"apt still works; a few package postinst scripts may print warnings.\")\n",
474
+ "\n",
475
+ " # -- build the customisation script ------------------------------------\n",
476
+ " recs = \"\" if CONFIG[\"APT_INSTALL_RECOMMENDS\"] else \"--no-install-recommends\"\n",
477
+ " K = CONFIG[\"KERNEL\"]\n",
478
+ " L = []\n",
479
+ " A = L.append\n",
480
+ " A(\"#!/bin/bash\")\n",
481
+ " A(\"# auto-generated by Cubic for Colab \u2014 change CONFIG in the notebook, not this file\")\n",
482
+ " A(\"export DEBIAN_FRONTEND=noninteractive HOME=/root LANG=C.UTF-8\")\n",
483
+ " A(\"FAIL=0; WARN=0\")\n",
484
+ " A(\"step(){ echo; echo \\\"===== $1 =====\\\"; }\")\n",
485
+ " A(\"ok(){ echo \\\"[CUBIC][OK] $1\\\"; }\")\n",
486
+ " A(\"bad(){ echo \\\"[CUBIC][FAIL] $1\\\"; FAIL=$((FAIL+1)); }\")\n",
487
+ " A(\"wrn(){ echo \\\"[CUBIC][WARN] $1\\\"; WARN=$((WARN+1)); }\")\n",
488
+ " A(\"step 'apt-get update'\")\n",
489
+ " A(\"apt-get update && ok apt-update || bad apt-update\")\n",
490
+ " for ppa in CONFIG[\"PPA_REPOS\"]:\n",
491
+ " A(f\"step 'PPA {ppa}'\")\n",
492
+ " A(f\"(command -v add-apt-repository >/dev/null 2>&1 || apt-get install -y software-properties-common) \"\n",
493
+ " f\"&& add-apt-repository -y '{ppa}' && apt-get update -q && ok 'PPA {ppa}' || bad 'PPA {ppa}'\")\n",
494
+ " for pkg in CONFIG[\"APT_INSTALL\"]:\n",
495
+ " A(f\"step 'apt-get install {pkg}'\")\n",
496
+ " A(f\"apt-get install -y {recs} '{pkg}' && ok 'install {pkg}' || bad 'install {pkg}'\")\n",
497
+ " for pkg in CONFIG[\"APT_PURGE\"]:\n",
498
+ " A(f\"step 'apt-get purge {pkg}'\")\n",
499
+ " A(f\"apt-get purge -y '{pkg}' && ok 'purge {pkg}' || bad 'purge {pkg}'\")\n",
500
+ " if CONFIG[\"DEB_URLS\"]:\n",
501
+ " A(\"step 'extra .deb packages'\")\n",
502
+ " A(\"okdebs=1; for d in /tmp/cubic-debs/*.deb; do dpkg -i \\\"$d\\\" || apt-get -f install -y || okdebs=0; done\")\n",
503
+ " A(\"[ \\\"$okdebs\\\" = 1 ] && ok debs || bad debs\")\n",
504
+ " if K.get(\"mode\") == \"install\":\n",
505
+ " A(f\"step 'kernel: install {K['package']}'\")\n",
506
+ " A(f\"apt-get install -y '{K['package']}' && ok kernel-install || bad kernel-install\")\n",
507
+ " if K.get(\"purge_old\"):\n",
508
+ " A(\"step 'kernel: purge old versions'\")\n",
509
+ " A(\"KVER=$(ls /lib/modules 2>/dev/null | sort -V | tail -1); \"\n",
510
+ " \"[ -n \\\"$KVER\\\" ] && { for p in $(dpkg-query -W -f='${Package}\\\\n' \"\n",
511
+ " \"'linux-image-[0-9]*' 'linux-image-unsigned-[0-9]*' 'linux-modules-[0-9]*' \"\n",
512
+ " \"'linux-headers-[0-9]*' 2>/dev/null); do case \\\"$p\\\" in *\\\"$KVER\\\"*) ;; *) \"\n",
513
+ " \"apt-get purge -y \\\"$p\\\" || true ;; esac; done; } ; wrn kernel-purge-done\")\n",
514
+ " for c in CONFIG[\"RUN_IN_CHROOT\"]:\n",
515
+ " A(\"step 'custom command'\")\n",
516
+ " A(f\"({c}) && ok custom || wrn custom\")\n",
517
+ " if CONFIG.get(\"SET_HOSTNAME\"):\n",
518
+ " A(f\"step 'hostname -> {_h}'\")\n",
519
+ " A(f\"echo '{_h}' > /etc/hostname && sed -i 's/127.0.1.1.*/127.0.1.1 {_h}/' /etc/hosts \"\n",
520
+ " \"&& ok hostname || bad hostname\")\n",
521
+ " if K.get(\"mode\") == \"install\" or K.get(\"purge_old\"):\n",
522
+ " A(\"step 'update-initramfs'\")\n",
523
+ " A(\"update-initramfs -u -k all && ok initramfs || wrn initramfs\")\n",
524
+ " A(\"step 'cleanup'\")\n",
525
+ " A(\"apt-get clean; apt-get autoremove -y >/dev/null 2>&1; \"\n",
526
+ " \"rm -rf /var/lib/apt/lists/* /tmp/cubic-debs /var/crash /tmp/cubic-customize.sh /tmp/*.deb\")\n",
527
+ " A(\"ok cleanup\")\n",
528
+ " A(\"echo; echo \\\"[CUBIC][FAIL] failures=$FAIL warnings=$WARN\\\"\")\n",
529
+ " A(\"exit 0\")\n",
530
+ " spath = os.path.join(SQUASH_DIR, \"tmp/cubic-customize.sh\")\n",
531
+ " os.makedirs(os.path.dirname(spath), exist_ok=True)\n",
532
+ " open(spath, \"w\").write(\"\\n\".join(L) + \"\\n\")\n",
533
+ " os.chmod(spath, 0o755)\n",
534
+ "\n",
535
+ " # -- run it --------------------------------------------------------------\n",
536
+ " if os.geteuid() != 0:\n",
537
+ " print(\"WARNING: not root \u2014 skipping the chroot execution. The generated script is at:\",\n",
538
+ " spath)\n",
539
+ " else:\n",
540
+ " log = os.path.join(WORK, \"chroot.log\")\n",
541
+ " print(\"Running the chroot customisation (watch the output below)\u2026\\n\")\n",
542
+ " subprocess.run(f\"bash -o pipefail -c \\\"chroot '{SQUASH_DIR}' /bin/bash /tmp/cubic-customize.sh \"\n",
543
+ " f\"2>&1 | tee '{log}'\\\"\", shell=True)\n",
544
+ " for b in binds:\n",
545
+ " subprocess.run(f\"umount '{b}'\", shell=True)\n",
546
+ " if resolv_was_link:\n",
547
+ " if os.path.isfile(resolv) and not os.path.islink(resolv):\n",
548
+ " os.remove(resolv)\n",
549
+ " elif os.path.isfile(resolv_bak):\n",
550
+ " shutil.move(resolv_bak, resolv)\n",
551
+ " fails = [ln.rstrip() for ln in open(log, errors=\"ignore\")\n",
552
+ " if ln.startswith(\"[CUBIC][FAIL]\") and \"failures=\" not in ln]\n",
553
+ " if fails:\n",
554
+ " print(\"\\n\".join(fails))\n",
555
+ " raise SystemExit(\"*** the chroot step reported failures above. Fix CONFIG and re-run \"\n",
556
+ " \"cell 5, then continue with cell 6. ***\")\n",
557
+ " print(\"\\nChroot customisation finished cleanly.\")\n",
558
+ " lap(\"chroot customisation\")\n",
559
+ "print(f\"Disk now: {disk_gb():.1f} GB free\")"
560
+ ]
561
+ },
562
+ {
563
+ "cell_type": "code",
564
+ "id": "15c6da929c74",
565
+ "metadata": {},
566
+ "execution_count": null,
567
+ "outputs": [],
568
+ "source": [
569
+ "# ==============================================================\n",
570
+ "# [6/8] REPACK SQUASHFS + PATCH THE ISO TREE\n",
571
+ "# ==============================================================\n",
572
+ "check_prereq(\"CONFIG\", \"SQUASH_DIR\", \"SQ_PATH\", \"META\", \"ISO_TREE\", \"run\")\n",
573
+ "\n",
574
+ "meta = json.load(open(META))\n",
575
+ "\n",
576
+ "# safety: no leftover bind-mounts from an interrupted cell 5\n",
577
+ "for _nm in (\"dev\", \"proc\", \"sys\"):\n",
578
+ " subprocess.run(f\"umount -f '{SQUASH_DIR}/{_nm}'\", shell=True)\n",
579
+ "\n",
580
+ "# -- refresh casper metadata (needs a working chroot) ----------------------\n",
581
+ "if os.geteuid() == 0 and os.path.isdir(SQUASH_DIR):\n",
582
+ " run(f\"chroot '{SQUASH_DIR}' dpkg-query -W -f='${{binary:Package}}\\t${{Version}}\\n' \"\n",
583
+ " f\"> '{ISO_TREE}/casper/filesystem.manifest'\", check=False)\n",
584
+ " _orig = os.path.join(WORK, \"orig.manifest\")\n",
585
+ " if os.path.isfile(_orig) and os.path.isfile(f\"{ISO_TREE}/casper/filesystem.manifest\"):\n",
586
+ " old = set(open(_orig, errors=\"ignore\").read().splitlines())\n",
587
+ " new = set(open(f\"{ISO_TREE}/casper/filesystem.manifest\", errors=\"ignore\").read().splitlines())\n",
588
+ " removed = sorted(old - new)\n",
589
+ " open(f\"{ISO_TREE}/casper/filesystem.manifest-remove\", \"w\").write(\n",
590
+ " \"\\n\".join(removed) + (\"\\n\" if removed else \"\"))\n",
591
+ " print(\"manifest refreshed;\", len(removed), \"package(s) removed vs original\")\n",
592
+ "else:\n",
593
+ " print(\"Keeping the original casper manifest (no usable chroot for dpkg-query).\")\n",
594
+ "run(f\"du -sb '{SQUASH_DIR}' | cut -f1 > '{ISO_TREE}/casper/filesystem.size'\", check=False)\n",
595
+ "\n",
596
+ "# -- repack the squashfs --------------------------------------------------\n",
597
+ "comp = CONFIG[\"SQUASH_COMPRESSION\"]\n",
598
+ "if comp == \"auto\":\n",
599
+ " base = meta.get(\"comp\", \"zstd\")\n",
600
+ " comp = base + {\"zstd\": \":19\", \"gzip\": \":9\", \"xz\": \"\"}.get(base, \"\")\n",
601
+ "cname, _, clvl = comp.partition(\":\")\n",
602
+ "flags = {\n",
603
+ " \"zstd\": f\"-comp zstd -b 1M -Xcompression-level {clvl or 19}\",\n",
604
+ " \"gzip\": f\"-comp gzip -b 1M -Xcompression-level {clvl or 9}\",\n",
605
+ " \"xz\": f\"-comp xz -b 1M -Xdict-size {clvl or '100%'}\",\n",
606
+ " \"lz4\": \"-comp lz4 -b 1M\",\n",
607
+ " \"lzo\": \"-comp lzo -b 1M\",\n",
608
+ "}.get(cname)\n",
609
+ "if not flags:\n",
610
+ " raise SystemExit(f\"*** unknown compression {comp!r} \u2014 use auto, zstd, gzip, xz or e.g. 'zstd:5' ***\")\n",
611
+ "NEW_SQ = SQ_PATH + \".new\"\n",
612
+ "if os.path.exists(NEW_SQ):\n",
613
+ " os.remove(NEW_SQ)\n",
614
+ "print(f\"Repacking {SQUASH_DIR} -> {os.path.basename(SQ_PATH)} [{flags}]\")\n",
615
+ "print(\"(this is the longest step \u2014 typically 10\u201340 min on free Colab)\")\n",
616
+ "run(f\"mksquashfs '{SQUASH_DIR}' '{NEW_SQ}' {flags} -noappend -no-recovery -always-use-fragments\")\n",
617
+ "os.replace(NEW_SQ, SQ_PATH)\n",
618
+ "print(f\"Replaced {os.path.basename(SQ_PATH)}: {os.path.getsize(SQ_PATH) / 1e9:.2f} GB\")\n",
619
+ "lap(\"squashfs repack\")\n",
620
+ "\n",
621
+ "# -- patch boot-menu titles ----------------------------------------------\n",
622
+ "edited_any = False\n",
623
+ "targets = [f\"{ISO_TREE}/boot/grub/grub.cfg\"] + sorted(glob.glob(f\"{ISO_TREE}/isolinux/*.cfg\"))\n",
624
+ "for t in targets:\n",
625
+ " if not os.path.isfile(t):\n",
626
+ " continue\n",
627
+ " txt = open(t, errors=\"ignore\").read()\n",
628
+ " new_txt = txt\n",
629
+ " for old, new in CONFIG[\"BOOT_MENU_EDITS\"]:\n",
630
+ " new_txt = new_txt.replace(old, new)\n",
631
+ " if new_txt != txt:\n",
632
+ " open(t, \"w\").write(new_txt)\n",
633
+ " print(\"patched:\", os.path.relpath(t, ISO_TREE))\n",
634
+ " edited_any = True\n",
635
+ "if CONFIG[\"BOOT_MENU_EDITS\"] and not edited_any:\n",
636
+ " print(\"WARNING: BOOT_MENU_EDITS matched nothing \u2014 the strings must appear (case-sensitive) \"\n",
637
+ " \"in boot/grub/grub.cfg.\")\n",
638
+ "\n",
639
+ "# -- drop extra files onto the ISO ----------------------------------------\n",
640
+ "for i, item in enumerate(CONFIG[\"ISO_FILES\"]):\n",
641
+ " if \"..\" in item[\"dst\"]:\n",
642
+ " raise SystemExit(\"*** ISO_FILES dst must not contain '..' ***\")\n",
643
+ " s = resolve_src(item[\"src\"], f\"isofile{i}\")\n",
644
+ " dst = os.path.join(ISO_TREE, item[\"dst\"].lstrip(\"/\"))\n",
645
+ " os.makedirs(os.path.dirname(dst) or ISO_TREE, exist_ok=True)\n",
646
+ " shutil.copy2(s, dst)\n",
647
+ " print(\"iso file :\", item[\"dst\"])\n",
648
+ "\n",
649
+ "# -- regenerate md5sum.txt -------------------------------------------------\n",
650
+ "md5tmp = os.path.join(WORK, \"md5sum.txt.new\")\n",
651
+ "run(f\"cd '{ISO_TREE}' && find . -type f -print0 | sort -z | xargs -0 md5sum > '{md5tmp}' \"\n",
652
+ " f\"&& mv '{md5tmp}' '{ISO_TREE}/md5sum.txt'\")\n",
653
+ "print(\"md5sum.txt regenerated\")\n",
654
+ "\n",
655
+ "if CONFIG.get(\"FREE_ROOTFS_AFTER_REPACK\", True):\n",
656
+ " shutil.rmtree(SQUASH_DIR, ignore_errors=True)\n",
657
+ " print(\"Removed the working rootfs copy to free disk (re-run cell 4 to unpack again).\")\n",
658
+ "print(f\"Disk now: {disk_gb():.1f} GB free\")"
659
+ ]
660
+ },
661
+ {
662
+ "cell_type": "code",
663
+ "id": "b409d3021793",
664
+ "metadata": {},
665
+ "execution_count": null,
666
+ "outputs": [],
667
+ "source": [
668
+ "# ==============================================================\n",
669
+ "# [7/8] REBUILD THE BOOTABLE ISO \u2014 xorriso, original boot layout\n",
670
+ "# ==============================================================\n",
671
+ "check_prereq(\"CONFIG\", \"ISO_TREE\", \"WORK\", \"META\", \"OUT_DIR\", \"run\")\n",
672
+ "\n",
673
+ "meta = json.load(open(META))\n",
674
+ "volid = meta.get(\"volid\") or \"UBUNTU_ISO\"\n",
675
+ "report = (meta.get(\"report\") or \"\").strip()\n",
676
+ "efi = os.path.join(ISO_TREE, \"boot/grub/efi.img\")\n",
677
+ "have_efi = os.path.isfile(efi)\n",
678
+ "\n",
679
+ "name = CONFIG[\"OUTPUT_NAME\"]\n",
680
+ "if not name.endswith(\".iso\"):\n",
681
+ " name += \".iso\"\n",
682
+ "OUT_ISO = os.path.join(OUT_DIR, name)\n",
683
+ "if os.path.exists(OUT_ISO):\n",
684
+ " os.remove(OUT_ISO)\n",
685
+ "\n",
686
+ "# grub2 MBR for the hybrid BIOS boot path\n",
687
+ "mbr = os.environ.get(\"CUBIC_GRUB2_MBR\") or \"/usr/lib/grub/i386-pc/boot_hybrid.img\"\n",
688
+ "if not os.path.isfile(mbr) and os.geteuid() == 0:\n",
689
+ " run(\"DEBIAN_FRONTEND=noninteractive apt-get install -y -q grub-pc-bin\")\n",
690
+ " mbr = os.environ.get(\"CUBIC_GRUB2_MBR\") or \"/usr/lib/grub/i386-pc/boot_hybrid.img\"\n",
691
+ "if not os.path.isfile(mbr):\n",
692
+ " raise SystemExit(\"*** boot_hybrid.img (grub-pc-bin) not found \u2014 required for BIOS boot. \"\n",
693
+ " \"Install grub-pc-bin or set CUBIC_GRUB2_MBR. ***\")\n",
694
+ "\n",
695
+ "def fix_report(rep):\n",
696
+ " \"\"\"Turn xorriso's own boot report of the ORIGINAL ISO into a fresh mkisofs\n",
697
+ " command for our modified tree.\"\"\"\n",
698
+ " args = []\n",
699
+ " for line in rep.splitlines():\n",
700
+ " line = line.strip()\n",
701
+ " if not line or line.startswith(\"-o \"):\n",
702
+ " continue\n",
703
+ " # make the El Torito EFI pointer dynamic: the whole appended partition\n",
704
+ " # (interval numbers use mixed units: 4724s = 2048-byte sectors, 2048d = 512-byte blocks)\n",
705
+ " line = re.sub(r\"appended_partition_(\\d+)_start_\\d+[sdb]_size_\\d+[sdb]\",\n",
706
+ " r\"appended_partition_\\1\", line)\n",
707
+ " # the report names a temporary copy of the ESP \u2014 point at our efi.img\n",
708
+ " m = re.match(r\"(--append_partition\\s+\\d+\\s+[0-9a-fA-F-]{36})\\s+\\S+$\", line)\n",
709
+ " if m:\n",
710
+ " if have_efi:\n",
711
+ " line = f\"{m.group(1)} '{efi}'\"\n",
712
+ " else:\n",
713
+ " continue\n",
714
+ " if line.startswith(\"--grub2-mbr\"):\n",
715
+ " p = line.split(None, 1)[1].strip().strip(\"'\\\"\")\n",
716
+ " if not os.path.isfile(p):\n",
717
+ " p = mbr\n",
718
+ " line = f\"--grub2-mbr '{p}'\"\n",
719
+ " args.append(line)\n",
720
+ " s = \" \".join(args)\n",
721
+ " if not re.search(r\"(^|\\s)-r(\\s|$)\", s):\n",
722
+ " s = \"-r \" + s\n",
723
+ " if \"-iso-level\" not in s:\n",
724
+ " s += \" --iso-level 3\"\n",
725
+ " if not re.search(r\"(^|\\s)-V(\\s|$)\", s):\n",
726
+ " s += f\" -V '{volid}'\"\n",
727
+ " if have_efi and \"--interval:appended_partition\" not in s and \"-e \" not in s:\n",
728
+ " s += \" -eltorito-alt-boot -e '--interval:appended_partition_2:::' -no-emul-boot\"\n",
729
+ " return s\n",
730
+ "\n",
731
+ "def static_args():\n",
732
+ " \"\"\"Fallback: the standard modern-Ubuntu hybrid layout.\"\"\"\n",
733
+ " a = [\"-r\", \"-V\", f\"'{volid}'\", \"--iso-level 3\", \"-joliet-long\"]\n",
734
+ " if (meta.get(\"boot\") or {}).get(\"partition_offset\") == 16:\n",
735
+ " a.append(\"--partition_offset 16\")\n",
736
+ " a += [\"-c boot.catalog\",\n",
737
+ " \"-b boot/grub/i386-pc/eltorito.img\", \"-no-emul-boot\",\n",
738
+ " \"-boot-load-size 4\", \"-boot-info-table\",\n",
739
+ " \"--eltorito-catalog boot/grub/boot.cat\",\n",
740
+ " \"--grub2-boot-info\", f\"--grub2-mbr '{mbr}'\", \"--mbr-force-bootable\"]\n",
741
+ " if have_efi:\n",
742
+ " a += [\"--append_partition 2 28732ac11ff8d211ba4b00a0c93ef938\", f\"'{efi}'\",\n",
743
+ " \"--appended_part_as_gpt\", \"-eltorito-alt-boot\",\n",
744
+ " \"-e\", \"'--interval:appended_partition_2:::'\", \"-no-emul-boot\"]\n",
745
+ " return \" \".join(a)\n",
746
+ "\n",
747
+ "if report:\n",
748
+ " print(\"Using the boot layout xorriso reported from the ORIGINAL ISO.\")\n",
749
+ " args = fix_report(report)\n",
750
+ "else:\n",
751
+ " print(\"Original boot report unavailable \u2014 using the standard Ubuntu hybrid layout.\")\n",
752
+ " args = static_args()\n",
753
+ "print(\"xorriso arguments:\\n \", args, \"\\n\")\n",
754
+ "print(\"Building the ISO (10\u201325 min for a desktop image)\u2026\")\n",
755
+ "run(f\"xorriso -as mkisofs -o '{OUT_ISO}' {args} '{ISO_TREE}'\")\n",
756
+ "lap(\"ISO rebuild\")\n",
757
+ "\n",
758
+ "# ---- verification --------------------------------------------------------\n",
759
+ "rep2 = subprocess.run(f\"xorriso -indev '{OUT_ISO}' -report_el_torito as_mkisofs\",\n",
760
+ " shell=True, capture_output=True, text=True).stdout.strip()\n",
761
+ "if rep2 and report:\n",
762
+ " def _norm(s):\n",
763
+ " s = re.sub(r\"'[^']*'\", \"Q\", s) # interval specs embed the image path\n",
764
+ " return re.sub(r\"\\d+\", \"0\", s)\n",
765
+ " print(\"Boot layout matches the original:\",\n",
766
+ " \"YES\" if _norm(rep2) == _norm(report) else \"no (see below)\")\n",
767
+ "if rep2:\n",
768
+ " print(rep2)\n",
769
+ "\n",
770
+ "new_boot = detect_boot_layout(OUT_ISO)\n",
771
+ "print(\"New ISO boot layout:\", new_boot)\n",
772
+ "if have_efi and new_boot.get(\"esp_bytes\"):\n",
773
+ " print(f\" EFI partition: {new_boot['esp_bytes'] / 1e6:.1f} MB \"\n",
774
+ " f\"(efi.img: {os.path.getsize(efi) / 1e6:.1f} MB)\")\n",
775
+ " with open(OUT_ISO, \"rb\") as f:\n",
776
+ " f.seek(new_boot[\"esp_first_lba\"] * 512)\n",
777
+ " esp_head = f.read(4096)\n",
778
+ " with open(efi, \"rb\") as f:\n",
779
+ " img_head = f.read(4096)\n",
780
+ " print(\" EFI partition content == efi.img:\", esp_head == img_head)\n",
781
+ "\n",
782
+ "chk = os.path.join(WORK, \"verify-grub.cfg\")\n",
783
+ "if os.path.isfile(f\"{ISO_TREE}/boot/grub/grub.cfg\"):\n",
784
+ " run(f\"xorriso -osirrox on -indev '{OUT_ISO}' -extract /boot/grub/grub.cfg '{chk}' -overwrite on\",\n",
785
+ " check=False)\n",
786
+ " if os.path.isfile(chk):\n",
787
+ " same = open(chk, errors=\"ignore\").read() == open(f\"{ISO_TREE}/boot/grub/grub.cfg\",\n",
788
+ " errors=\"ignore\").read()\n",
789
+ " print(\"grub.cfg readable from the new ISO, identical to the tree:\", same)\n",
790
+ "\n",
791
+ "print(\"Computing SHA256\u2026\")\n",
792
+ "h = hashlib.sha256()\n",
793
+ "with open(OUT_ISO, \"rb\") as f:\n",
794
+ " for chunk in iter(lambda: f.read(1 << 22), b\"\"):\n",
795
+ " h.update(chunk)\n",
796
+ "open(OUT_ISO + \".sha256\", \"w\").write(f\"{h.hexdigest()} {os.path.basename(OUT_ISO)}\\n\")\n",
797
+ "print(\"SHA256:\", h.hexdigest())\n",
798
+ "print(f\"Disk now: {disk_gb():.1f} GB free\")"
799
+ ]
800
+ },
801
+ {
802
+ "cell_type": "code",
803
+ "id": "47dc3bb9ec99",
804
+ "metadata": {},
805
+ "execution_count": null,
806
+ "outputs": [],
807
+ "source": [
808
+ "# ==============================================================\n",
809
+ "# [8/8] SAVE THE RESULT \u2014 Google Drive and/or browser download\n",
810
+ "# ==============================================================\n",
811
+ "check_prereq(\"CONFIG\", \"OUT_ISO\")\n",
812
+ "\n",
813
+ "out = CONFIG.get(\"OUTPUT\", {})\n",
814
+ "artifacts = [OUT_ISO, OUT_ISO + \".sha256\"]\n",
815
+ "\n",
816
+ "if out.get(\"gdrive\", True):\n",
817
+ " if IN_COLAB:\n",
818
+ " from google.colab import drive\n",
819
+ " drive.mount(\"/content/drive\", force_remount=True)\n",
820
+ " dst_dir = \"/content/drive/MyDrive/CubicColab\"\n",
821
+ " os.makedirs(dst_dir, exist_ok=True)\n",
822
+ " for a in artifacts:\n",
823
+ " print(\"copying\", a, \"to Drive (may take a few minutes)\u2026\")\n",
824
+ " shutil.copy2(a, dst_dir)\n",
825
+ " print(\"Saved to Google Drive:\", dst_dir)\n",
826
+ " else:\n",
827
+ " print(\"Not in Colab \u2014 leaving the files in\", OUT_DIR)\n",
828
+ "\n",
829
+ "if out.get(\"browser_download\"):\n",
830
+ " if IN_COLAB:\n",
831
+ " from google.colab import files\n",
832
+ " files.download(OUT_ISO)\n",
833
+ " else:\n",
834
+ " print(\"Browser download only works in Colab \u2014 the file is at\", OUT_ISO)\n",
835
+ "\n",
836
+ "print()\n",
837
+ "print(\"=\" * 62)\n",
838
+ "print(\"FINAL ISO :\", OUT_ISO)\n",
839
+ "print(\"SIZE : %.2f GB\" % (os.path.getsize(OUT_ISO) / 1e9))\n",
840
+ "print(\"SHA256 :\", open(OUT_ISO + \".sha256\").read().strip())\n",
841
+ "print(\"ELAPSED : %.1f min\" % ((time.monotonic() - _T0) / 60))\n",
842
+ "print(\"=\" * 62)\n",
843
+ "print(\"Flash it with balenaEtcher / Rufus / dd, or boot it in a VM. Enjoy!\")"
844
+ ]
845
+ },
846
+ {
847
+ "cell_type": "markdown",
848
+ "id": "21a025213a4f",
849
+ "metadata": {},
850
+ "source": [
851
+ "## Troubleshooting & FAQ\n",
852
+ "\n",
853
+ "**Re-run map** \u2014 after changing `CONFIG`, re-run:\n",
854
+ "\n",
855
+ "- packages / files / kernel / hostname / PPA \u2192 cells **4 \u2192 5 \u2192 6 \u2192 7 \u2192 8**\n",
856
+ "- only boot-menu titles or ISO files \u2192 cells **6 \u2192 7 \u2192 8**\n",
857
+ "- only the output target \u2192 cell **8**\n",
858
+ "\n",
859
+ "**`command failed ... No space left on device`** \u2014 a desktop build wants ~30 GB.\n",
860
+ "Set `KEEP_SOURCE_ISO = False`, pick a smaller ISO (Lubuntu, server), or\n",
861
+ "`Runtime \u25b8 Disconnect and delete runtime` and try again.\n",
862
+ "\n",
863
+ "**`SHA256 MISMATCH`** \u2014 the download broke. Delete `WORK_ROOT/source.iso` and re-run cell 3.\n",
864
+ "\n",
865
+ "**Warnings about `/proc` or bind-mounts in the chroot step** \u2014 harmless when the runtime does not\n",
866
+ "allow mounts; apt still works and the squashfs is repacked regardless.\n",
867
+ "\n",
868
+ "**Boot-menu edit did not apply** \u2014 the strings are case-sensitive and must appear in\n",
869
+ "`boot/grub/grub.cfg`. Inspect with `!grep -n \"menuentry\" /content/cubic-work/iso-tree/boot/grub/grub.cfg`.\n",
870
+ "\n",
871
+ "**Will it boot?** The BIOS (El Torito + grub2 MBR) and UEFI (GPT ESP / EFI image) boot equipment is\n",
872
+ "reproduced from the original ISO \u2014 cell 7 prints the new ISO's boot report next to the original's so\n",
873
+ "you can see it matches. Always smoke-test the result in a VM (GNOME Boxes, VirtualBox, QEMU) before\n",
874
+ "flashing it with balenaEtcher / Rufus / `dd`.\n",
875
+ "\n",
876
+ "**Ubuntu Server?** Yes \u2014 the pipeline edits the largest squashfs layer, exactly like Cubic does.\n",
877
+ "\n",
878
+ "**Where is my ISO?** `WORK_ROOT/output/`, plus `Google Drive \u25b8 MyDrive \u25b8 CubicColab` when\n",
879
+ "`OUTPUT[\"gdrive\"]` is on. The `.sha256` sidecar sits next to it.\n",
880
+ "\n",
881
+ "**Command-line use?** The repo also ships `cubic_pipeline.py` \u2014 the exact same pipeline as a plain\n",
882
+ "script for any root Linux box: edit `CONFIG`, run `sudo python3 cubic_pipeline.py`."
883
+ ]
884
+ }
885
+ ]
886
+ }
cubic_pipeline.py ADDED
@@ -0,0 +1,739 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Cubic for Colab — no-GUI custom Ubuntu ISO creator (CLI twin of the notebook).
4
+
5
+ Usage (as root on a Debian/Ubuntu machine, or inside Google Colab):
6
+ sudo python3 cubic_pipeline.py
7
+
8
+ Edit the CONFIG dict below first. The full log of the chroot step lands in
9
+ WORK_ROOT/chroot.log. Generated from cubic_colab.ipynb — both stay in sync
10
+ by construction.
11
+ """
12
+ import os, sys
13
+
14
+ # stop here when not root (apt/chroot need it); Colab runs as root already
15
+ if os.geteuid() != 0:
16
+ sys.exit("Please run as root: sudo python3 cubic_pipeline.py")
17
+
18
+ #----------------------------------------------------------------------
19
+ # cell 1/8
20
+ #----------------------------------------------------------------------
21
+
22
+ # ==============================================================
23
+ # [1/8] CONFIGURATION — edit the values below, then
24
+ # Runtime â–¸ Run all (or run the cells one by one)
25
+ # ==============================================================
26
+ CONFIG = {
27
+ # ---- source ISO --------------------------------------------------
28
+ # Any of:
29
+ # "https://releases.ubuntu.com/24.04/ubuntu-24.04.5.1-desktop-amd64.iso"
30
+ # "/content/ubuntu-24.04.5.1-desktop-amd64.iso" (uploaded via the Files panel)
31
+ # "gdrive:ISOs/ubuntu-24.04.5.1-desktop-amd64.iso" (a file in your Google Drive)
32
+ "ISO_SOURCE": "https://releases.ubuntu.com/24.04/ubuntu-24.04.5.1-desktop-amd64.iso",
33
+
34
+ # Integrity check: a SHA256SUMS URL, a literal hash, or None to skip.
35
+ "ISO_SHA256": "https://releases.ubuntu.com/24.04/SHA256SUMS",
36
+
37
+ # ---- workspace -----------------------------------------------------
38
+ "WORK_ROOT": "/content/cubic-work", # scratch space; needs ~2.5 x ISO size
39
+ "KEEP_SOURCE_ISO": True, # False = delete the downloaded .iso after extracting (saves disk)
40
+ "FREE_ROOTFS_AFTER_REPACK": True, # False = keep the unpacked rootfs for another edit round
41
+
42
+ # ---- live-system customisations (inside the squashfs) ---------------
43
+ "APT_INSTALL": ["vim", "htop"], # packages to add, e.g. ["vlc", "gimp"]
44
+ "APT_INSTALL_RECOMMENDS": True, # also install recommended packages
45
+ "APT_PURGE": [], # packages to remove, e.g. ["thunderbird"]
46
+ "PPA_REPOS": [], # e.g. ["ppa:mozillateam/ppa"]
47
+ "DEB_URLS": [], # direct .deb URLs, installed with dpkg -i
48
+ "ROOTFS_FILES": [], # {"src": "/content/me.png", "dst": "/usr/share/backgrounds/me.png", "mode": "0644"}
49
+ "RUN_IN_CHROOT": [], # extra shell one-liners, e.g. ["apt-get install -y git"]
50
+ "SET_HOSTNAME": "", # e.g. "my-ubuntu"
51
+
52
+ # Kernel handling:
53
+ # mode "keep" -> ship the kernel the ISO came with
54
+ # mode "install" -> apt-install the package below (e.g. a newer HWE kernel)
55
+ "KERNEL": {"mode": "keep", "package": "linux-generic-hwe-24.04", "purge_old": False},
56
+
57
+ # ---- ISO-level customisations ---------------------------------------
58
+ "BOOT_MENU_EDITS": [], # [ ["Try or Install Ubuntu", "Try or Install My Ubuntu"], ... ]
59
+ "ISO_FILES": [], # {"src": "/content/extra.cfg", "dst": "/extra.cfg"} (paths on the ISO)
60
+
61
+ # ---- repack & result --------------------------------------------------
62
+ "SQUASH_COMPRESSION": "auto", # auto | zstd | gzip | xz | e.g. "zstd:5"
63
+ "OUTPUT_NAME": "custom-ubuntu.iso",
64
+ "OUTPUT": {"gdrive": True, # copy the result to Drive > MyDrive > CubicColab
65
+ "browser_download": False} # also pop a browser download (for ISOs < ~2 GB)
66
+ }
67
+
68
+ def _show_config(c=CONFIG):
69
+ print(f" source ISO : {c['ISO_SOURCE']}")
70
+ print(f" sha256 check : {c['ISO_SHA256'] or 'skipped'}")
71
+ print(f" work dir : {c['WORK_ROOT']}")
72
+ print(f" apt install/purge : {c['APT_INSTALL']} / {c['APT_PURGE']}")
73
+ print(f" PPAs / deb URLs : {c['PPA_REPOS']} / {len(c['DEB_URLS'])} file(s)")
74
+ print(f" rootfs/iso files : {len(c['ROOTFS_FILES'])} / {len(c['ISO_FILES'])}")
75
+ print(f" kernel : {c['KERNEL']}")
76
+ print(f" hostname : {c['SET_HOSTNAME'] or 'unchanged'}")
77
+ print(f" boot-menu edits : {len(c['BOOT_MENU_EDITS'])}")
78
+ print(f" compression : {c['SQUASH_COMPRESSION']}")
79
+ print(f" output : {c['OUTPUT_NAME']} {c['OUTPUT']}")
80
+
81
+ _show_config()
82
+ print("\nCONFIG loaded. Everything except ISO_SOURCE is optional.")
83
+
84
+ #----------------------------------------------------------------------
85
+ # cell 2/8
86
+ #----------------------------------------------------------------------
87
+
88
+ # ==============================================================
89
+ # [2/8] ENVIRONMENT SETUP — install tools, create the workspace
90
+ # ==============================================================
91
+ import os, sys, glob, re, json, shutil, subprocess, time, struct, hashlib
92
+
93
+ IN_COLAB = False
94
+ try:
95
+ from google.colab import drive, files # noqa: F401
96
+ IN_COLAB = True
97
+ except Exception:
98
+ pass
99
+
100
+ WORK = CONFIG["WORK_ROOT"]
101
+ SRC_ISO = os.path.join(WORK, "source.iso")
102
+ ISO_TREE = os.path.join(WORK, "iso-tree")
103
+ SQUASH_DIR = os.path.join(WORK, "rootfs-edit")
104
+ OUT_DIR = os.path.join(WORK, "output")
105
+ META = os.path.join(WORK, "build-meta.json")
106
+ for _d in (WORK, ISO_TREE, SQUASH_DIR, OUT_DIR):
107
+ os.makedirs(_d, exist_ok=True)
108
+
109
+ _T0 = time.monotonic()
110
+ def lap(label):
111
+ print(f"[timer] {label}: {(time.monotonic() - _T0) / 60:.1f} min elapsed")
112
+
113
+ def disk_gb(path="/"):
114
+ return shutil.disk_usage(path).free / 1e9
115
+
116
+ def run(cmd, check=True, quiet=False):
117
+ """Run a shell command, stream its output, abort the cell on failure."""
118
+ if not quiet:
119
+ print("$ " + cmd)
120
+ r = subprocess.run(cmd, shell=True)
121
+ if check and r.returncode != 0:
122
+ raise SystemExit(f"\n*** command failed (exit {r.returncode}). Fix it and re-run this cell. ***")
123
+ return r.returncode
124
+
125
+ def check_prereq(*names):
126
+ missing = [n for n in names if n not in globals()]
127
+ if missing:
128
+ raise SystemExit(f"*** run the earlier cell(s) first — missing: {', '.join(missing)} ***")
129
+
130
+ def resolve_src(src, tag="file"):
131
+ """Local path or URL -> local path."""
132
+ if src.startswith("http"):
133
+ p = os.path.join(WORK, "dl-" + tag)
134
+ run(f"wget -q -O '{p}' '{src}'")
135
+ return p
136
+ if os.path.isfile(src):
137
+ return src
138
+ raise SystemExit(f"*** source not found: {src} ***")
139
+
140
+ def read_pvd_volume_id(path):
141
+ """Volume label straight from the ISO9660 primary volume descriptor."""
142
+ with open(path, "rb") as f:
143
+ for off in (32768, 16 * 2048): # plain and partition_offset=16 layouts
144
+ f.seek(off)
145
+ pvd = f.read(2048)
146
+ if pvd[1:6] == b"CD001" and pvd[0:1] == b"\x01":
147
+ return pvd[40:72].decode("ascii", "replace").strip()
148
+ return "UBUNTU_ISO"
149
+
150
+ def detect_boot_layout(path):
151
+ """MBR/GPT facts we may need to reproduce the hybrid boot setup."""
152
+ info = {"partition_offset": 0, "gpt": False, "esp_bytes": None, "esp_first_lba": None}
153
+ try:
154
+ with open(path, "rb") as f:
155
+ f.seek(446 + 8)
156
+ if struct.unpack("<I", f.read(4))[0] * 512 == 16 * 2048:
157
+ info["partition_offset"] = 16
158
+ f.seek(512)
159
+ hdr = f.read(512)
160
+ if hdr[:8] == b"EFI PART":
161
+ info["gpt"] = True
162
+ n = struct.unpack_from("<I", hdr, 80)[0]
163
+ esz = struct.unpack_from("<I", hdr, 84)[0]
164
+ ent_lba = struct.unpack_from("<Q", hdr, 72)[0]
165
+ f.seek(ent_lba * 512)
166
+ ents = f.read(min(n, 128) * esz)
167
+ if n >= 1 and struct.unpack_from("<Q", ents, 32)[0] * 512 == 16 * 2048:
168
+ info["partition_offset"] = 16
169
+ if n >= 2:
170
+ first = struct.unpack_from("<Q", ents, esz + 32)[0]
171
+ last = struct.unpack_from("<Q", ents, esz + 40)[0]
172
+ info["esp_first_lba"] = first
173
+ info["esp_bytes"] = (last - first + 1) * 512
174
+ except Exception as e:
175
+ print("boot-layout detection warning:", e)
176
+ return info
177
+
178
+ print(f"Python {sys.version.split()[0]} | Colab: {IN_COLAB} | root: {os.geteuid() == 0}")
179
+ print(f"Disk: {disk_gb():.1f} GB free on /")
180
+ if os.geteuid() != 0:
181
+ print("WARNING: not running as root — apt/chroot will fail. In Colab you are root by default.")
182
+ if disk_gb() < 15:
183
+ print("WARNING: < 15 GB free. A desktop-ISO build wants ~30 GB; server/Lubuntu builds ~16 GB.")
184
+
185
+ if os.geteuid() == 0:
186
+ run("apt-get update -q")
187
+ run("DEBIAN_FRONTEND=noninteractive apt-get install -y -q "
188
+ "squashfs-tools xorriso mtools libarchive-tools grub-pc-bin")
189
+ else:
190
+ print("Not root: skipping apt — ensure squashfs-tools, xorriso and grub-pc-bin are installed.")
191
+ print("Tools ready. Workspace:", WORK)
192
+
193
+ #----------------------------------------------------------------------
194
+ # cell 3/8
195
+ #----------------------------------------------------------------------
196
+
197
+ # ==============================================================
198
+ # [3/8] GET THE SOURCE ISO — download / Google Drive / uploaded file
199
+ # ==============================================================
200
+ check_prereq("CONFIG", "SRC_ISO", "WORK", "run")
201
+
202
+ src = CONFIG["ISO_SOURCE"]
203
+ DOWNLOADED = False
204
+ if src.startswith("http"):
205
+ print("Downloading ISO (resumable — be patient)…")
206
+ run(f"wget -c -q --show-progress -O '{SRC_ISO}' '{src}'")
207
+ DOWNLOADED = True
208
+ elif src.startswith("gdrive:"):
209
+ if not IN_COLAB:
210
+ raise SystemExit("*** gdrive: sources only work in Colab ***")
211
+ from google.colab import drive
212
+ drive.mount("/content/drive", force_remount=True)
213
+ gd = "/content/drive/MyDrive/" + src.split(":", 1)[1].lstrip("/")
214
+ if not os.path.isfile(gd):
215
+ raise SystemExit(f"*** not found in Google Drive: {gd} ***")
216
+ print("Copying out of Drive…")
217
+ shutil.copy2(gd, SRC_ISO)
218
+ elif os.path.isfile(src):
219
+ SRC_ISO = src
220
+ else:
221
+ raise SystemExit("*** ISO_SOURCE not found. Upload the .iso via the Files panel (left sidebar) "
222
+ "and point CONFIG['ISO_SOURCE'] at it, or use a URL. ***")
223
+
224
+ print(f"ISO ready: {SRC_ISO} ({os.path.getsize(SRC_ISO) / 1e9:.2f} GB)")
225
+
226
+ chk = CONFIG.get("ISO_SHA256")
227
+ if chk:
228
+ h = hashlib.sha256()
229
+ with open(SRC_ISO, "rb") as f:
230
+ for chunk in iter(lambda: f.read(1 << 22), b""):
231
+ h.update(chunk)
232
+ actual = h.hexdigest()
233
+ expected = None
234
+ if chk.startswith("http"):
235
+ sums = os.path.join(WORK, "SHA256SUMS")
236
+ run(f"wget -q -O '{sums}' '{chk}'", check=False)
237
+ base = os.path.basename(SRC_ISO)
238
+ for line in open(sums, errors="ignore"):
239
+ parts = line.split()
240
+ if len(parts) == 2 and parts[1].lstrip("*") == base:
241
+ expected = parts[0].lower()
242
+ break
243
+ if expected is None:
244
+ print("WARNING: no entry for this file in SHA256SUMS — verification skipped")
245
+ else:
246
+ expected = chk.strip().lower()
247
+ if expected:
248
+ if expected != actual:
249
+ raise SystemExit("*** SHA256 MISMATCH — the download is corrupt.\n"
250
+ f" expected {expected}\n actual {actual}\n"
251
+ f" Delete {SRC_ISO} and re-run this cell. ***")
252
+ print("SHA256 verified:", actual)
253
+
254
+ #----------------------------------------------------------------------
255
+ # cell 4/8
256
+ #----------------------------------------------------------------------
257
+
258
+ # ==============================================================
259
+ # [4/8] EXTRACT — unpack the ISO and its live filesystem
260
+ # (pure file operations, nothing is mounted)
261
+ # ==============================================================
262
+ check_prereq("CONFIG", "SRC_ISO", "ISO_TREE", "SQUASH_DIR", "DOWNLOADED", "run")
263
+
264
+ if os.path.isdir(ISO_TREE):
265
+ subprocess.run(f"chmod -R u+w '{ISO_TREE}' 2>/dev/null", shell=True)
266
+ shutil.rmtree(ISO_TREE)
267
+ if os.path.isdir(SQUASH_DIR):
268
+ subprocess.run(f"chmod -R u+w '{SQUASH_DIR}' 2>/dev/null", shell=True)
269
+ shutil.rmtree(SQUASH_DIR)
270
+
271
+ print("Extracting the ISO tree with xorriso (no loop-mount needed)…")
272
+ run(f"xorriso -osirrox on -indev '{SRC_ISO}' -extract / '{ISO_TREE}'")
273
+ run(f"chmod -R u+w '{ISO_TREE}'") # xorriso restores files read-only
274
+ lap("ISO tree extraction")
275
+
276
+ print("Looking for the casper squashfs…")
277
+ cands = sorted(glob.glob(f"{ISO_TREE}/casper/*.squashfs")
278
+ + glob.glob(f"{ISO_TREE}/*/casper/*.squashfs")
279
+ + glob.glob(f"{ISO_TREE}/live/*.squashfs"),
280
+ key=os.path.getsize)
281
+ if not cands:
282
+ raise SystemExit("*** no casper/live squashfs found — is this really an Ubuntu live ISO? ***")
283
+ SQ_PATH = max(cands, key=os.path.getsize)
284
+ print("Found:", ", ".join(os.path.basename(c) for c in cands), "-> editing", os.path.basename(SQ_PATH))
285
+ if len(cands) > 1:
286
+ print("NOTE: several squashfs layers present; only the largest one is edited (like Cubic does).")
287
+
288
+ _s = subprocess.run(f"unsquashfs -s '{SQ_PATH}'", shell=True, capture_output=True, text=True).stdout
289
+ _m = re.search(r"Compression (\w+)", _s)
290
+ SQUASH_COMP = _m.group(1) if _m else "zstd"
291
+ print("Original squashfs compression:", SQUASH_COMP)
292
+
293
+ print("Unpacking the live filesystem (several minutes on first run)…")
294
+ run(f"unsquashfs -d '{SQUASH_DIR}' '{SQ_PATH}'")
295
+ lap("squashfs extraction")
296
+
297
+ # metadata for the rebuild step
298
+ _rep = subprocess.run(f"xorriso -indev '{SRC_ISO}' -report_el_torito as_mkisofs",
299
+ shell=True, capture_output=True, text=True)
300
+ json.dump({
301
+ "volid": read_pvd_volume_id(SRC_ISO),
302
+ "report": _rep.stdout,
303
+ "comp": SQUASH_COMP,
304
+ "boot": detect_boot_layout(SRC_ISO),
305
+ "sq_name": os.path.basename(SQ_PATH),
306
+ }, open(META, "w"))
307
+ _mf = f"{ISO_TREE}/casper/filesystem.manifest"
308
+ if os.path.isfile(_mf):
309
+ _om = os.path.join(WORK, "orig.manifest")
310
+ if os.path.exists(_om):
311
+ os.chmod(_om, 0o644) # copy2 preserves read-only modes
312
+ shutil.copy2(_mf, _om)
313
+ os.chmod(_om, 0o644)
314
+
315
+ if (not CONFIG["KEEP_SOURCE_ISO"]) and DOWNLOADED and os.path.exists(SRC_ISO):
316
+ os.remove(SRC_ISO)
317
+ print("Source ISO deleted to free disk (KEEP_SOURCE_ISO=False).")
318
+
319
+ print(f"Disk now: {disk_gb():.1f} GB free")
320
+
321
+ #----------------------------------------------------------------------
322
+ # cell 5/8
323
+ #----------------------------------------------------------------------
324
+
325
+ # ==============================================================
326
+ # [5/8] CUSTOMISE THE LIVE SYSTEM — apt, PPAs, files, kernel, chroot
327
+ # ==============================================================
328
+ check_prereq("CONFIG", "SQUASH_DIR", "WORK", "run")
329
+
330
+ def _safe(tok, pat, what):
331
+ if not re.match(pat, tok):
332
+ raise SystemExit(f"*** invalid {what}: {tok!r} ***")
333
+
334
+ for _p in CONFIG["APT_INSTALL"] + CONFIG["APT_PURGE"]:
335
+ _safe(_p, r"^[A-Za-z0-9._+:-]+$", "package name")
336
+ for _p in CONFIG["PPA_REPOS"]:
337
+ _safe(_p, r"^(ppa:[A-Za-z0-9._/-]+|https?://\S+)$", "PPA")
338
+ _h = CONFIG.get("SET_HOSTNAME", "")
339
+ if _h:
340
+ _safe(_h, r"^[A-Za-z0-9][A-Za-z0-9.-]*$", "hostname")
341
+
342
+ did_any = bool(CONFIG["APT_INSTALL"] or CONFIG["APT_PURGE"] or CONFIG["PPA_REPOS"]
343
+ or CONFIG["DEB_URLS"] or CONFIG["ROOTFS_FILES"] or CONFIG["RUN_IN_CHROOT"]
344
+ or CONFIG.get("SET_HOSTNAME")
345
+ or CONFIG["KERNEL"].get("mode") == "install" or CONFIG["KERNEL"].get("purge_old"))
346
+
347
+ if not did_any:
348
+ print("No live-system customisations configured — skipping this step.")
349
+ else:
350
+ # -- copy files into the rootfs / fetch .deb files --------------------
351
+ debdir = os.path.join(SQUASH_DIR, "tmp/cubic-debs")
352
+ os.makedirs(debdir, exist_ok=True)
353
+ for i, item in enumerate(CONFIG["ROOTFS_FILES"]):
354
+ s = resolve_src(item["src"], f"rootfs{i}")
355
+ dst = os.path.join(SQUASH_DIR, item["dst"].lstrip("/"))
356
+ os.makedirs(os.path.dirname(dst), exist_ok=True)
357
+ shutil.copy2(s, dst)
358
+ if item.get("mode"):
359
+ os.chmod(dst, int(item["mode"], 8))
360
+ print("rootfs file :", item["dst"])
361
+ for i, u in enumerate(CONFIG["DEB_URLS"]):
362
+ run(f"wget -q -O '{debdir}/extra{i}.deb' '{u}'")
363
+
364
+ # -- DNS for the chroot ------------------------------------------------
365
+ resolv = os.path.join(SQUASH_DIR, "etc/resolv.conf")
366
+ resolv_was_link = os.path.islink(resolv)
367
+ resolv_bak = resolv + ".cubicbak"
368
+ if not resolv_was_link and os.path.isfile(resolv):
369
+ shutil.copy2(resolv, resolv_bak)
370
+ with open(resolv, "w") as f:
371
+ f.write("nameserver 8.8.8.8\nnameserver 1.1.1.1\n")
372
+
373
+ # -- bind /dev /proc /sys (best effort; apt works without them) --------
374
+ binds = []
375
+ for nm in ("dev", "proc", "sys"):
376
+ if subprocess.run(f"mount --bind /{nm} '{SQUASH_DIR}/{nm}'", shell=True).returncode == 0:
377
+ binds.append(f"{SQUASH_DIR}/{nm}")
378
+ if len(binds) < 3:
379
+ print("NOTE: /dev /proc /sys bind-mounts unavailable here — the chroot runs without them. "
380
+ "apt still works; a few package postinst scripts may print warnings.")
381
+
382
+ # -- build the customisation script ------------------------------------
383
+ recs = "" if CONFIG["APT_INSTALL_RECOMMENDS"] else "--no-install-recommends"
384
+ K = CONFIG["KERNEL"]
385
+ L = []
386
+ A = L.append
387
+ A("#!/bin/bash")
388
+ A("# auto-generated by Cubic for Colab — change CONFIG in the notebook, not this file")
389
+ A("export DEBIAN_FRONTEND=noninteractive HOME=/root LANG=C.UTF-8")
390
+ A("FAIL=0; WARN=0")
391
+ A("step(){ echo; echo \"===== $1 =====\"; }")
392
+ A("ok(){ echo \"[CUBIC][OK] $1\"; }")
393
+ A("bad(){ echo \"[CUBIC][FAIL] $1\"; FAIL=$((FAIL+1)); }")
394
+ A("wrn(){ echo \"[CUBIC][WARN] $1\"; WARN=$((WARN+1)); }")
395
+ A("step 'apt-get update'")
396
+ A("apt-get update && ok apt-update || bad apt-update")
397
+ for ppa in CONFIG["PPA_REPOS"]:
398
+ A(f"step 'PPA {ppa}'")
399
+ A(f"(command -v add-apt-repository >/dev/null 2>&1 || apt-get install -y software-properties-common) "
400
+ f"&& add-apt-repository -y '{ppa}' && apt-get update -q && ok 'PPA {ppa}' || bad 'PPA {ppa}'")
401
+ for pkg in CONFIG["APT_INSTALL"]:
402
+ A(f"step 'apt-get install {pkg}'")
403
+ A(f"apt-get install -y {recs} '{pkg}' && ok 'install {pkg}' || bad 'install {pkg}'")
404
+ for pkg in CONFIG["APT_PURGE"]:
405
+ A(f"step 'apt-get purge {pkg}'")
406
+ A(f"apt-get purge -y '{pkg}' && ok 'purge {pkg}' || bad 'purge {pkg}'")
407
+ if CONFIG["DEB_URLS"]:
408
+ A("step 'extra .deb packages'")
409
+ A("okdebs=1; for d in /tmp/cubic-debs/*.deb; do dpkg -i \"$d\" || apt-get -f install -y || okdebs=0; done")
410
+ A("[ \"$okdebs\" = 1 ] && ok debs || bad debs")
411
+ if K.get("mode") == "install":
412
+ A(f"step 'kernel: install {K['package']}'")
413
+ A(f"apt-get install -y '{K['package']}' && ok kernel-install || bad kernel-install")
414
+ if K.get("purge_old"):
415
+ A("step 'kernel: purge old versions'")
416
+ A("KVER=$(ls /lib/modules 2>/dev/null | sort -V | tail -1); "
417
+ "[ -n \"$KVER\" ] && { for p in $(dpkg-query -W -f='${Package}\\n' "
418
+ "'linux-image-[0-9]*' 'linux-image-unsigned-[0-9]*' 'linux-modules-[0-9]*' "
419
+ "'linux-headers-[0-9]*' 2>/dev/null); do case \"$p\" in *\"$KVER\"*) ;; *) "
420
+ "apt-get purge -y \"$p\" || true ;; esac; done; } ; wrn kernel-purge-done")
421
+ for c in CONFIG["RUN_IN_CHROOT"]:
422
+ A("step 'custom command'")
423
+ A(f"({c}) && ok custom || wrn custom")
424
+ if CONFIG.get("SET_HOSTNAME"):
425
+ A(f"step 'hostname -> {_h}'")
426
+ A(f"echo '{_h}' > /etc/hostname && sed -i 's/127.0.1.1.*/127.0.1.1 {_h}/' /etc/hosts "
427
+ "&& ok hostname || bad hostname")
428
+ if K.get("mode") == "install" or K.get("purge_old"):
429
+ A("step 'update-initramfs'")
430
+ A("update-initramfs -u -k all && ok initramfs || wrn initramfs")
431
+ A("step 'cleanup'")
432
+ A("apt-get clean; apt-get autoremove -y >/dev/null 2>&1; "
433
+ "rm -rf /var/lib/apt/lists/* /tmp/cubic-debs /var/crash /tmp/cubic-customize.sh /tmp/*.deb")
434
+ A("ok cleanup")
435
+ A("echo; echo \"[CUBIC][FAIL] failures=$FAIL warnings=$WARN\"")
436
+ A("exit 0")
437
+ spath = os.path.join(SQUASH_DIR, "tmp/cubic-customize.sh")
438
+ os.makedirs(os.path.dirname(spath), exist_ok=True)
439
+ open(spath, "w").write("\n".join(L) + "\n")
440
+ os.chmod(spath, 0o755)
441
+
442
+ # -- run it --------------------------------------------------------------
443
+ if os.geteuid() != 0:
444
+ print("WARNING: not root — skipping the chroot execution. The generated script is at:",
445
+ spath)
446
+ else:
447
+ log = os.path.join(WORK, "chroot.log")
448
+ print("Running the chroot customisation (watch the output below)…\n")
449
+ subprocess.run(f"bash -o pipefail -c \"chroot '{SQUASH_DIR}' /bin/bash /tmp/cubic-customize.sh "
450
+ f"2>&1 | tee '{log}'\"", shell=True)
451
+ for b in binds:
452
+ subprocess.run(f"umount '{b}'", shell=True)
453
+ if resolv_was_link:
454
+ if os.path.isfile(resolv) and not os.path.islink(resolv):
455
+ os.remove(resolv)
456
+ elif os.path.isfile(resolv_bak):
457
+ shutil.move(resolv_bak, resolv)
458
+ fails = [ln.rstrip() for ln in open(log, errors="ignore")
459
+ if ln.startswith("[CUBIC][FAIL]") and "failures=" not in ln]
460
+ if fails:
461
+ print("\n".join(fails))
462
+ raise SystemExit("*** the chroot step reported failures above. Fix CONFIG and re-run "
463
+ "cell 5, then continue with cell 6. ***")
464
+ print("\nChroot customisation finished cleanly.")
465
+ lap("chroot customisation")
466
+ print(f"Disk now: {disk_gb():.1f} GB free")
467
+
468
+ #----------------------------------------------------------------------
469
+ # cell 6/8
470
+ #----------------------------------------------------------------------
471
+
472
+ # ==============================================================
473
+ # [6/8] REPACK SQUASHFS + PATCH THE ISO TREE
474
+ # ==============================================================
475
+ check_prereq("CONFIG", "SQUASH_DIR", "SQ_PATH", "META", "ISO_TREE", "run")
476
+
477
+ meta = json.load(open(META))
478
+
479
+ # safety: no leftover bind-mounts from an interrupted cell 5
480
+ for _nm in ("dev", "proc", "sys"):
481
+ subprocess.run(f"umount -f '{SQUASH_DIR}/{_nm}'", shell=True)
482
+
483
+ # -- refresh casper metadata (needs a working chroot) ----------------------
484
+ if os.geteuid() == 0 and os.path.isdir(SQUASH_DIR):
485
+ run(f"chroot '{SQUASH_DIR}' dpkg-query -W -f='${{binary:Package}}\t${{Version}}\n' "
486
+ f"> '{ISO_TREE}/casper/filesystem.manifest'", check=False)
487
+ _orig = os.path.join(WORK, "orig.manifest")
488
+ if os.path.isfile(_orig) and os.path.isfile(f"{ISO_TREE}/casper/filesystem.manifest"):
489
+ old = set(open(_orig, errors="ignore").read().splitlines())
490
+ new = set(open(f"{ISO_TREE}/casper/filesystem.manifest", errors="ignore").read().splitlines())
491
+ removed = sorted(old - new)
492
+ open(f"{ISO_TREE}/casper/filesystem.manifest-remove", "w").write(
493
+ "\n".join(removed) + ("\n" if removed else ""))
494
+ print("manifest refreshed;", len(removed), "package(s) removed vs original")
495
+ else:
496
+ print("Keeping the original casper manifest (no usable chroot for dpkg-query).")
497
+ run(f"du -sb '{SQUASH_DIR}' | cut -f1 > '{ISO_TREE}/casper/filesystem.size'", check=False)
498
+
499
+ # -- repack the squashfs --------------------------------------------------
500
+ comp = CONFIG["SQUASH_COMPRESSION"]
501
+ if comp == "auto":
502
+ base = meta.get("comp", "zstd")
503
+ comp = base + {"zstd": ":19", "gzip": ":9", "xz": ""}.get(base, "")
504
+ cname, _, clvl = comp.partition(":")
505
+ flags = {
506
+ "zstd": f"-comp zstd -b 1M -Xcompression-level {clvl or 19}",
507
+ "gzip": f"-comp gzip -b 1M -Xcompression-level {clvl or 9}",
508
+ "xz": f"-comp xz -b 1M -Xdict-size {clvl or '100%'}",
509
+ "lz4": "-comp lz4 -b 1M",
510
+ "lzo": "-comp lzo -b 1M",
511
+ }.get(cname)
512
+ if not flags:
513
+ raise SystemExit(f"*** unknown compression {comp!r} — use auto, zstd, gzip, xz or e.g. 'zstd:5' ***")
514
+ NEW_SQ = SQ_PATH + ".new"
515
+ if os.path.exists(NEW_SQ):
516
+ os.remove(NEW_SQ)
517
+ print(f"Repacking {SQUASH_DIR} -> {os.path.basename(SQ_PATH)} [{flags}]")
518
+ print("(this is the longest step — typically 10–40 min on free Colab)")
519
+ run(f"mksquashfs '{SQUASH_DIR}' '{NEW_SQ}' {flags} -noappend -no-recovery -always-use-fragments")
520
+ os.replace(NEW_SQ, SQ_PATH)
521
+ print(f"Replaced {os.path.basename(SQ_PATH)}: {os.path.getsize(SQ_PATH) / 1e9:.2f} GB")
522
+ lap("squashfs repack")
523
+
524
+ # -- patch boot-menu titles ----------------------------------------------
525
+ edited_any = False
526
+ targets = [f"{ISO_TREE}/boot/grub/grub.cfg"] + sorted(glob.glob(f"{ISO_TREE}/isolinux/*.cfg"))
527
+ for t in targets:
528
+ if not os.path.isfile(t):
529
+ continue
530
+ txt = open(t, errors="ignore").read()
531
+ new_txt = txt
532
+ for old, new in CONFIG["BOOT_MENU_EDITS"]:
533
+ new_txt = new_txt.replace(old, new)
534
+ if new_txt != txt:
535
+ open(t, "w").write(new_txt)
536
+ print("patched:", os.path.relpath(t, ISO_TREE))
537
+ edited_any = True
538
+ if CONFIG["BOOT_MENU_EDITS"] and not edited_any:
539
+ print("WARNING: BOOT_MENU_EDITS matched nothing — the strings must appear (case-sensitive) "
540
+ "in boot/grub/grub.cfg.")
541
+
542
+ # -- drop extra files onto the ISO ----------------------------------------
543
+ for i, item in enumerate(CONFIG["ISO_FILES"]):
544
+ if ".." in item["dst"]:
545
+ raise SystemExit("*** ISO_FILES dst must not contain '..' ***")
546
+ s = resolve_src(item["src"], f"isofile{i}")
547
+ dst = os.path.join(ISO_TREE, item["dst"].lstrip("/"))
548
+ os.makedirs(os.path.dirname(dst) or ISO_TREE, exist_ok=True)
549
+ shutil.copy2(s, dst)
550
+ print("iso file :", item["dst"])
551
+
552
+ # -- regenerate md5sum.txt -------------------------------------------------
553
+ md5tmp = os.path.join(WORK, "md5sum.txt.new")
554
+ run(f"cd '{ISO_TREE}' && find . -type f -print0 | sort -z | xargs -0 md5sum > '{md5tmp}' "
555
+ f"&& mv '{md5tmp}' '{ISO_TREE}/md5sum.txt'")
556
+ print("md5sum.txt regenerated")
557
+
558
+ if CONFIG.get("FREE_ROOTFS_AFTER_REPACK", True):
559
+ shutil.rmtree(SQUASH_DIR, ignore_errors=True)
560
+ print("Removed the working rootfs copy to free disk (re-run cell 4 to unpack again).")
561
+ print(f"Disk now: {disk_gb():.1f} GB free")
562
+
563
+ #----------------------------------------------------------------------
564
+ # cell 7/8
565
+ #----------------------------------------------------------------------
566
+
567
+ # ==============================================================
568
+ # [7/8] REBUILD THE BOOTABLE ISO — xorriso, original boot layout
569
+ # ==============================================================
570
+ check_prereq("CONFIG", "ISO_TREE", "WORK", "META", "OUT_DIR", "run")
571
+
572
+ meta = json.load(open(META))
573
+ volid = meta.get("volid") or "UBUNTU_ISO"
574
+ report = (meta.get("report") or "").strip()
575
+ efi = os.path.join(ISO_TREE, "boot/grub/efi.img")
576
+ have_efi = os.path.isfile(efi)
577
+
578
+ name = CONFIG["OUTPUT_NAME"]
579
+ if not name.endswith(".iso"):
580
+ name += ".iso"
581
+ OUT_ISO = os.path.join(OUT_DIR, name)
582
+ if os.path.exists(OUT_ISO):
583
+ os.remove(OUT_ISO)
584
+
585
+ # grub2 MBR for the hybrid BIOS boot path
586
+ mbr = os.environ.get("CUBIC_GRUB2_MBR") or "/usr/lib/grub/i386-pc/boot_hybrid.img"
587
+ if not os.path.isfile(mbr) and os.geteuid() == 0:
588
+ run("DEBIAN_FRONTEND=noninteractive apt-get install -y -q grub-pc-bin")
589
+ mbr = os.environ.get("CUBIC_GRUB2_MBR") or "/usr/lib/grub/i386-pc/boot_hybrid.img"
590
+ if not os.path.isfile(mbr):
591
+ raise SystemExit("*** boot_hybrid.img (grub-pc-bin) not found — required for BIOS boot. "
592
+ "Install grub-pc-bin or set CUBIC_GRUB2_MBR. ***")
593
+
594
+ def fix_report(rep):
595
+ """Turn xorriso's own boot report of the ORIGINAL ISO into a fresh mkisofs
596
+ command for our modified tree."""
597
+ args = []
598
+ for line in rep.splitlines():
599
+ line = line.strip()
600
+ if not line or line.startswith("-o "):
601
+ continue
602
+ # make the El Torito EFI pointer dynamic: the whole appended partition
603
+ # (interval numbers use mixed units: 4724s = 2048-byte sectors, 2048d = 512-byte blocks)
604
+ line = re.sub(r"appended_partition_(\d+)_start_\d+[sdb]_size_\d+[sdb]",
605
+ r"appended_partition_\1", line)
606
+ # the report names a temporary copy of the ESP — point at our efi.img
607
+ m = re.match(r"(--append_partition\s+\d+\s+[0-9a-fA-F-]{36})\s+\S+$", line)
608
+ if m:
609
+ if have_efi:
610
+ line = f"{m.group(1)} '{efi}'"
611
+ else:
612
+ continue
613
+ if line.startswith("--grub2-mbr"):
614
+ p = line.split(None, 1)[1].strip().strip("'\"")
615
+ if not os.path.isfile(p):
616
+ p = mbr
617
+ line = f"--grub2-mbr '{p}'"
618
+ args.append(line)
619
+ s = " ".join(args)
620
+ if not re.search(r"(^|\s)-r(\s|$)", s):
621
+ s = "-r " + s
622
+ if "-iso-level" not in s:
623
+ s += " --iso-level 3"
624
+ if not re.search(r"(^|\s)-V(\s|$)", s):
625
+ s += f" -V '{volid}'"
626
+ if have_efi and "--interval:appended_partition" not in s and "-e " not in s:
627
+ s += " -eltorito-alt-boot -e '--interval:appended_partition_2:::' -no-emul-boot"
628
+ return s
629
+
630
+ def static_args():
631
+ """Fallback: the standard modern-Ubuntu hybrid layout."""
632
+ a = ["-r", "-V", f"'{volid}'", "--iso-level 3", "-joliet-long"]
633
+ if (meta.get("boot") or {}).get("partition_offset") == 16:
634
+ a.append("--partition_offset 16")
635
+ a += ["-c boot.catalog",
636
+ "-b boot/grub/i386-pc/eltorito.img", "-no-emul-boot",
637
+ "-boot-load-size 4", "-boot-info-table",
638
+ "--eltorito-catalog boot/grub/boot.cat",
639
+ "--grub2-boot-info", f"--grub2-mbr '{mbr}'", "--mbr-force-bootable"]
640
+ if have_efi:
641
+ a += ["--append_partition 2 28732ac11ff8d211ba4b00a0c93ef938", f"'{efi}'",
642
+ "--appended_part_as_gpt", "-eltorito-alt-boot",
643
+ "-e", "'--interval:appended_partition_2:::'", "-no-emul-boot"]
644
+ return " ".join(a)
645
+
646
+ if report:
647
+ print("Using the boot layout xorriso reported from the ORIGINAL ISO.")
648
+ args = fix_report(report)
649
+ else:
650
+ print("Original boot report unavailable — using the standard Ubuntu hybrid layout.")
651
+ args = static_args()
652
+ print("xorriso arguments:\n ", args, "\n")
653
+ print("Building the ISO (10–25 min for a desktop image)…")
654
+ run(f"xorriso -as mkisofs -o '{OUT_ISO}' {args} '{ISO_TREE}'")
655
+ lap("ISO rebuild")
656
+
657
+ # ---- verification --------------------------------------------------------
658
+ rep2 = subprocess.run(f"xorriso -indev '{OUT_ISO}' -report_el_torito as_mkisofs",
659
+ shell=True, capture_output=True, text=True).stdout.strip()
660
+ if rep2 and report:
661
+ def _norm(s):
662
+ s = re.sub(r"'[^']*'", "Q", s) # interval specs embed the image path
663
+ return re.sub(r"\d+", "0", s)
664
+ print("Boot layout matches the original:",
665
+ "YES" if _norm(rep2) == _norm(report) else "no (see below)")
666
+ if rep2:
667
+ print(rep2)
668
+
669
+ new_boot = detect_boot_layout(OUT_ISO)
670
+ print("New ISO boot layout:", new_boot)
671
+ if have_efi and new_boot.get("esp_bytes"):
672
+ print(f" EFI partition: {new_boot['esp_bytes'] / 1e6:.1f} MB "
673
+ f"(efi.img: {os.path.getsize(efi) / 1e6:.1f} MB)")
674
+ with open(OUT_ISO, "rb") as f:
675
+ f.seek(new_boot["esp_first_lba"] * 512)
676
+ esp_head = f.read(4096)
677
+ with open(efi, "rb") as f:
678
+ img_head = f.read(4096)
679
+ print(" EFI partition content == efi.img:", esp_head == img_head)
680
+
681
+ chk = os.path.join(WORK, "verify-grub.cfg")
682
+ if os.path.isfile(f"{ISO_TREE}/boot/grub/grub.cfg"):
683
+ run(f"xorriso -osirrox on -indev '{OUT_ISO}' -extract /boot/grub/grub.cfg '{chk}' -overwrite on",
684
+ check=False)
685
+ if os.path.isfile(chk):
686
+ same = open(chk, errors="ignore").read() == open(f"{ISO_TREE}/boot/grub/grub.cfg",
687
+ errors="ignore").read()
688
+ print("grub.cfg readable from the new ISO, identical to the tree:", same)
689
+
690
+ print("Computing SHA256…")
691
+ h = hashlib.sha256()
692
+ with open(OUT_ISO, "rb") as f:
693
+ for chunk in iter(lambda: f.read(1 << 22), b""):
694
+ h.update(chunk)
695
+ open(OUT_ISO + ".sha256", "w").write(f"{h.hexdigest()} {os.path.basename(OUT_ISO)}\n")
696
+ print("SHA256:", h.hexdigest())
697
+ print(f"Disk now: {disk_gb():.1f} GB free")
698
+
699
+ #----------------------------------------------------------------------
700
+ # cell 8/8
701
+ #----------------------------------------------------------------------
702
+
703
+ # ==============================================================
704
+ # [8/8] SAVE THE RESULT — Google Drive and/or browser download
705
+ # ==============================================================
706
+ check_prereq("CONFIG", "OUT_ISO")
707
+
708
+ out = CONFIG.get("OUTPUT", {})
709
+ artifacts = [OUT_ISO, OUT_ISO + ".sha256"]
710
+
711
+ if out.get("gdrive", True):
712
+ if IN_COLAB:
713
+ from google.colab import drive
714
+ drive.mount("/content/drive", force_remount=True)
715
+ dst_dir = "/content/drive/MyDrive/CubicColab"
716
+ os.makedirs(dst_dir, exist_ok=True)
717
+ for a in artifacts:
718
+ print("copying", a, "to Drive (may take a few minutes)…")
719
+ shutil.copy2(a, dst_dir)
720
+ print("Saved to Google Drive:", dst_dir)
721
+ else:
722
+ print("Not in Colab — leaving the files in", OUT_DIR)
723
+
724
+ if out.get("browser_download"):
725
+ if IN_COLAB:
726
+ from google.colab import files
727
+ files.download(OUT_ISO)
728
+ else:
729
+ print("Browser download only works in Colab — the file is at", OUT_ISO)
730
+
731
+ print()
732
+ print("=" * 62)
733
+ print("FINAL ISO :", OUT_ISO)
734
+ print("SIZE : %.2f GB" % (os.path.getsize(OUT_ISO) / 1e9))
735
+ print("SHA256 :", open(OUT_ISO + ".sha256").read().strip())
736
+ print("ELAPSED : %.1f min" % ((time.monotonic() - _T0) / 60))
737
+ print("=" * 62)
738
+ print("Flash it with balenaEtcher / Rufus / dd, or boot it in a VM. Enjoy!")
739
+