9 Commits
Author SHA1 Message Date
Mistercoolertyper be6379107f tests: strengthen T17's over-grant check, add T21 modes, cross-file contract in T19
T17's package-remove assertion could not fire: it used a sleeper that had already
exited, so pkcheck returned 127 and the check printed 'info' rather than a
verdict. A negative assertion that cannot fail is worse than none. It now owns a
sleeper (setsid + exec -a, pid confirmed via /proc before pkcheck is trusted),
and 127 or any unexpected code is a FAIL rather than a pass. Verified capable of
failing by injecting package-remove into the rule: pkcheck went rc=2 -> rc=0 and
the assertion went red; the rule was then restored (sha256 unchanged).

T21 asserts both scripts are recorded as 100755 in the index. core.fileMode=false
means a Windows checkout silently drops the executable bit, so a fresh Linux
clone got non-executable files.

T19 now reads update_local_repo.OFFLINE_UPDATE_SCRIPT and asserts the preseed
names the same path. Both files hard-code it, and nothing tied them together, so
a rename would leave auto_update.sh printing 'not installed yet' with everything
else green.

Final: 107 passed, 0 failed, 2 skipped. The skips stay honest (T12 needs gpg;
T13's ks.cfg assertion is vacuous because the file is not in the repo).
2026-11-04 10:38:17 +01:00
Mistercoolertyper e9a447da4d preseed: bring the readable vdi-post.sh copy back in line with what runs
15d6518 rewrote the late_command payload (inline pkcon sequence -> delegation to
/usr/local/sbin/vdi-offline-update, plus enabling vdi-offline-update.timer) but
left the readable comment copy of the same script ~100 lines above it unchanged.
The two are meant to be the same script, so anyone reading preseed.cfg to learn
what a Debian install does was reading something that no longer matched the
payload. Caught by 8cc5's validator, which compares them byte-for-byte.

No behaviour change: the runtime payload was already correct. Also fixes a stale
comment - packagekit-tools was described as being used by /root/auto_update.sh,
which now delegates; the helper is what calls pkcon, and packagekit-tools is
still required for it.

Verified independently by running the reassembled late_command against a fake
/target: the generated script is 70 lines, parses, delegates, contains no inline
pkcon sequence, enables the timer, and is byte-identical to the comment copy.

Also tightens the README's claim about other updaters: unattended-upgrades is
absent, and apt.systemd.daily gates every install step on 'command -v
unattended-upgrade', so apt-daily-upgrade only refreshes the index. Checked
rather than asserted.
2026-11-04 10:38:13 +01:00
Mistercoolertyper 96815c5ffb git: record debian/make-iso.sh and debian/test/run-tests.sh as executable
core.fileMode=false on a Windows checkout, so git never picked up the executable
bit from disk. Both files are 100755 in the index now; a fresh Linux clone gets
them runnable instead of needing chmod.
2026-11-04 10:30:48 +01:00
Mistercoolertyper 402fea66fd tests: cover polkit rule, offline-update timer, preseed generation and ISO build
Adds T16-T20 to the Debian harness (103 passed, 0 failed, 2 skipped):

T16  the polkit rule is installed, mode 644, covers the two update actions,
     does not over-grant package-remove/reinstall/untrusted, and is idempotent.
T17  the real decision, in both directions: a sudo-group user is authorised
     (pkcheck rc=0) with the rule, and still prompted (rc=2) without it. The
     control is the point - without it the test cannot fail.
T18  vdi-offline-update: bash -n, unit verification, the throttle stamp, that
     a second run is skipped, that a stale stamp lets it run, that pkcon exit 5
     is reported as 'no updates available' rather than a download failure, and
     that /system-update is never armed without a prepared payload.
T19  the preseed still generates a script that parses, delegates to
     vdi-offline-update instead of an inline pkcon sequence, and enables cron
     and the timer.
T20  make-iso.sh: refuses to overwrite its input or an existing output, then
     checks the built image - preseed byte-identical, all 40 kernel lines
     patched, gtk.cfg patched, no doubled parameters, El Torito present with
     both BIOS and UEFI images, no source file missing, and size within 16MB of
     the original (the bloat regression).

Skips stay honest: T12 needs gpg, T13's ks.cfg assertion is vacuous because
the file was never in the repo.
2026-11-04 10:30:30 +01:00
Mistercoolertyper 15d65183dc Debian: passwordless updates, offline updates, and install ISO builder
Ports the update behaviour of the Fedora clients to Debian, and adds the
Debian equivalent of putting ks.cfg on the installation medium.

Updates
-------
Debian's shipped polkit policy only lets a sudo-group user trigger
upgrade-system and trigger-offline-update without a password. The actions
pkcon refresh and pkcon update actually use (system-sources-refresh and
system-update) are auth_admin, so a desktop user was prompted - a
behavioural difference from Fedora. update_local_repo.py now installs
/etc/polkit-1/rules.d/60-vdi-no-password-updates.rules granting exactly
those two plus package-install to group sudo. package-remove,
package-reinstall and package-install-untrusted stay auth_admin.

The offline update itself ports unchanged: Debian 13 PackageKit 1.3.1
supports offline-get-prepared and offline-trigger, and
packagekit-offline-update.service is wired into system-update.target.
Scheduling moves from an @reboot cron line to vdi-offline-update.timer
(6h, Persistent), with /root/auto_update.sh delegating to the same script
so there is one implementation instead of two.

Both are installed by update_local_repo.py, not only by the preseed, so
already-provisioned machines pick them up on their next 10-minute cron run.

install ISO
-----------
debian/make-iso.sh bakes preseed.cfg into a Debian netinst ISO and adds
auto=true priority=critical preseed/file=/cdrom/preseed.cfg to every boot
menu entry, then verifies its own output.

Measured, not assumed
---------------------
* subject.local == true never matches in this environment: pkcheck returns
  2 with the clause and 0 without it, same sudo-group user. It was in the
  first version of the rule and is removed; the reasoning is in the source.
* pkcon exits 5 for "no packages to update", which is the normal answer on
  a patched box and was being logged as a download failure. Fixed.
* offline-get-prepared exits 4 when nothing is prepared, so the Fedora
  "if ... offline-trigger" guard is load-bearing - triggering anyway can
  leave a dangling /system-update symlink that breaks the next boot.
* Extracting a netinst and rebuilding with "xorriso -as mkisofs" grows it
  792MB -> 988MB because Debian shares identical file extents; replaying
  the original session with -map keeps dedup and the boot record.
* A hardcoded menu list misses isolinux/gtk.cfg, where the BIOS *default*
  entry lives, so the machine still prompted. Menus are discovered now.

Tests: 90 passed, 0 failed, 2 skipped. T17 asserts the polkit decision in
both directions (authorised with the rule, prompted without it), because a
check that cannot fail proves nothing.
2026-11-04 10:16:23 +01:00
Mistercoolertyper 4f1a4530aa Serialise concurrent harness runs and purge stale apt indexes
Two runs of the harness share /var/lib/apt/lists and /etc/apt/sources.list.d.
With two in flight, one run's teardown deleted the other's temp repo while apt
was reading it, producing 'Could not open file .../vdi-debian-test.<other>' -
a failure that looks like a port bug but is a collision. Take a flock for the
duration of the run, and clear indexes left by earlier runs whose temp
directory no longer exists.
2026-11-04 09:25:17 +01:00
Mistercoolertyper 6ddb1d251a Add Debian 13 (trixie) support alongside Fedora
The provisioning path now runs on both package families. Fedora behaviour is
unchanged: the Fedora publishing code issues the same ten operations in the
same order as before, verified by recording the call sequence from both
implementations against a stubbed environment.

update_local_repo.py
  Detects the family from /etc/os-release and dispatches to sync_fedora() or
  sync_debian(). Release assets are filtered by extension, so neither family
  sees the other's packages. The Debian path builds a flat apt-ftparchive
  repository at the same /var/local/citrix-repo, publishes
  local-citrix-repo.list, and runs apt-get update.

  Fixes found while testing:
  - tqdm is now an optional dependency. A stock Debian 13 image has no pip and
    no tqdm, and dying at import would take down provisioning over a progress
    bar.
  - sync_debian prunes stale *.deb files before repopulating. The Fedora path
    gets this for free by writing fixed filenames; Debian filenames carry the
    version, so without pruning every old version stayed indexed and apt always
    picked the highest, making rollback impossible.
  - The apt source file is resolved next to the script rather than from the
    working directory, with a hardcoded canonical fallback, so a foreign cwd or
    a missing file cannot break the 10-minute cron job.

local-citrix-repo.list
  The apt counterpart of local-citrix-repo.repo, which stays as-is for dnf.
  Uses trusted=yes rather than a signature: the repository is generated on the
  machine from packages this script downloaded itself, so a signature would only
  prove the machine signed its own work, and it would add a gpg dependency that
  Debian 13 does not ship by default. Index integrity is still enforced through
  the hashes in Release.

debian/preseed.cfg
  The debian-installer equivalent of ks.cfg. Same locale, keyboard, timezone,
  passwords, inventory-derived hostname/user/password, disk auto-detection,
  Firefox managed bookmarks, Citrix and TeamViewer installs, auto-update script,
  cron jobs and disable-sleep unit. Every directive was checked against the
  templates in the real trixie udebs. Documented gaps, all inherent to preseed
  vs kickstart: uppercase usernames are rejected by user-setup and so are
  created in late_command; d-i has no lsblk, openssl, chvt or openvt, so disk
  detection reads /sys/block and the inventory prompt goes to /dev/console with
  a kernel-cmdline override and a timeout; pip install tqdm becomes
  python3-tqdm from apt because of PEP 668.

debian/test/
  Harness covering the Debian path on a real Debian 13 machine: repo build,
  sources.list validity, apt visibility after purging the list cache, install
  resolution, idempotency, stale-package pruning, corrupt-index rejection, and
  Fedora non-regression. 52 pass, 3 skip (each skip states why).

Known limitations are listed in README.md under "What the tests do NOT prove":
no real d-i install has been run, and the generated post-install script is
verified as well-formed rather than executed against a target root.
2026-11-04 09:24:57 +01:00
OpenCode 5d9b278270 Apply Plasma 6.8 KDE settings on existing clients 2026-11-03 11:39:01 +01:00
lwagner2 ceae480ba0 Update update_local_repo.py 2026-07-23 14:58:48 +02:00
8 changed files with 5020 additions and 47 deletions

No files matched your search

+431
View File
@@ -1 +1,432 @@
# VDI-Linux
Provisioning for the REYHER VDI clients. Two package families are supported from
this branch:
| | Fedora | Debian |
|---|---|---|
| installer input | `ks.cfg` (Anaconda kickstart) | `debian/preseed.cfg` (debian-installer) |
| desktop | `@^kde-desktop-environment` | `kde-desktop` task |
| Citrix packages | `ICAClient.rpm`, `ctxusb.rpm` | `icaclient`, `ctxusb` |
| local repo build | `createrepo_c` | `apt-ftparchive` |
| local repo config | `/etc/yum.repos.d/local-citrix-repo.repo` | `/etc/apt/sources.list.d/local-citrix-repo.list` |
| repo refresh | `dnf makecache` | `apt-get update` |
| browser | `firefox` | `firefox-esr` |
`update_local_repo.py` picks the path itself from `/etc/os-release`, so the same
file and the same cron job work on both. `configure_kde.py` is distro-neutral and
runs unchanged on both.
## What runs, and when
1. The installer provisions the base system from `ks.cfg` or `debian/preseed.cfg`.
2. A `%post` / `late_command` step writes the Firefox managed bookmarks, clones
this repository to `/root/VDI-Linux`, installs TeamViewer, writes
`/root/auto_update.sh`, installs the `disable-sleep` systemd unit, and adds the
cron jobs.
3. A cron job runs `update_local_repo.py` every 10 minutes as root. That script
pulls this repo, applies the KDE settings, downloads the newest Citrix
packages from the Gitea release, republishes the local repository, and
refreshes the package manager's index.
4. `@reboot` runs `/root/auto_update.sh` once the network is up, which
pre-downloads system updates and prepares an offline update.
## update_local_repo.py
```
detect_package_family() /etc/os-release -> "fedora" | "debian"
main() git pull, apply KDE settings, desktop shortcut,
is_newer_release(), then sync_fedora() or sync_debian()
```
`fetch_release_info()` filters release assets by the running family's extension,
so a Fedora client never sees the `.deb` assets and a Debian client never sees the
`.rpm` assets. Both families read the same Gitea release.
### Fedora path
Unchanged from the previously deployed version. Fixed asset filenames
(`ctxusb.rpm`, `ICAClient.rpm`) are downloaded into `/temp/packages`, copied into
`/var/local/citrix-repo`, indexed with `createrepo_c`, and published with
`local-citrix-repo.repo` (`gpgcheck=1` against the imported
`RPM-GPG-KEY-citrix-local`), then `dnf makecache` and `pkcon refresh force`.
This path was verified to issue the same ten operations in the same order with
the same arguments as `main`, by running both implementations against a stubbed
environment and diffing the recorded call sequence. See "Regression testing".
### Debian path
The Debian assets are named with the version embedded
(`icaclient_26.08.0.225_amd64.deb`), so they are matched by package-name prefix
rather than by exact filename. They are downloaded, copied into the same
`/var/local/citrix-repo`, and indexed with
```sh
cd /var/local/citrix-repo
apt-ftparchive packages . > Packages
gzip -c Packages > Packages.gz
apt-ftparchive release . > Release
```
That is a flat ("trivial") apt archive: the packages, `Packages`, `Packages.gz`
and `Release` all sit directly in the directory, with no `dists/` tree. apt reads
it through `local-citrix-repo.list`:
```
deb [trusted=yes] file:/var/local/citrix-repo ./
```
The suite is `./` - a path ending in a slash, no component - which is what marks
a flat repository.
**Why `trusted=yes` and not a signed repository.** The Fedora side signs because
it already has an RPM key. On Debian the repository is generated on the machine,
from packages this script has just downloaded itself, so a signature would only
prove that the machine signed its own work. Signing would also add a real
dependency: Debian 13 has no `gpg` installed by default, and apt verifies with
`sqv` (Sequoia) rather than `gpgv`, so generating and trusting a key inside a
d-i install is a new failure mode for no gain.
`trusted=yes` does **not** disable integrity checking. It tells apt not to
require a signature over the `Release` file; apt still verifies every index file
against the hashes in `Release`, and a tampered `Packages` fails with
`E: Failed to fetch ... Hash Sum mismatch`. What it gives up is proof of
*authorship*, which is meaningless for a repository the machine builds from its
own downloads.
**Stale packages are pruned.** The Fedora path writes fixed filenames, so a new
release overwrites the old ones and the repository can never hold two versions.
Debian filenames carry the version, so `sync_debian()` deletes every `*.deb` from
the repository directory before repopulating it. Without that, every previous
version would stay indexed and apt would always pick the highest, making a
rollback by publishing an older build impossible.
**Refreshing the index.** apt has no per-source equivalent of dnf's
`metadata_expire`; the index is re-read only when `apt-get update` runs.
`sync_debian()` runs it after rebuilding, and the 10-minute cron job runs
`sync_debian()`, so the index does not go stale in practice.
### Where the `.deb` files come from
1. Assets attached to the newest Gitea release, matched by package-name prefix.
2. If the release has no `.deb` assets, `$VDI_DEB_DIR` (default
`/temp/packages/deb`), so an operator can stage the two files on the machine
without publishing a release.
If neither has them the script fails with a message naming both places. It does
not fall back to converting the RPMs: `alien` is unmaintained and would break the
Citrix pre/post-install scripts, which is a worse outcome than a clear failure.
### Runtime requirements on Debian
`apt-utils` (for `apt-ftparchive`), `python3`, `git`, and optionally
`python3-tqdm`. `tqdm` is only the download progress bar and the script falls
back to a no-op if it is missing, but without `apt-utils` or `python3` the cron
job fails every 10 minutes with the reason only visible in
`/var/log/update_local_repo.log`.
## Updates
The Fedora clients update through PackageKit: `pkcon refresh`, `pkcon update`, and
an offline update that is downloaded in the background and applied at the next
boot. Debian does the same, with one addition (a polkit rule) and one rewrite (the
scheduler).
### Updating without a password
A user in the `sudo` group can refresh and install updates from the desktop
without being asked for a password, as on Fedora. This needs a polkit rule,
because Debian's shipped policy does not cover it:
- `/usr/share/polkit-1/rules.d/org.freedesktop.packagekit.rules` grants passwordless
access only to `upgrade-system` and `trigger-offline-update`.
- `system-sources-refresh` (what `pkcon refresh` uses) and `system-update` (what
`pkcon update` uses) are `auth_admin`, so a desktop user *is* prompted.
- `/usr/share/polkit-1/rules.d/50-default.rules` makes `unix-group:sudo` the admin
identity, so the prompt is for the user's own password.
`update_local_repo.py` therefore installs
`/etc/polkit-1/rules.d/60-vdi-no-password-updates.rules`, allowing
`system-sources-refresh`, `system-update` and `package-install` for members of
group `sudo`. Deliberately **not** granted: `package-remove`,
`package-reinstall`, `package-install-untrusted` - a normal user still cannot
remove packages or install an untrusted one without a password.
Measured with `pkcheck`: with the rule, `pkcheck --action-id
org.freedesktop.packagekit.system-sources-refresh` returns 0 (authorised); with the
rule removed it returns 2 (authentication required). The test harness asserts both
directions, because a check that cannot fail proves nothing.
One thing that did *not* work and is worth knowing: the rule was first written
with `subject.local == true`, to limit it to seats physically in front of the
machine. That clause never matches in this environment - the rule silently did
nothing and users were still prompted - so it was removed and the reasoning is
recorded in the source. The consequence is that a `sudo`-group user on a remote
session can also update without a password, which is the same trust level that
group already has through `sudo`.
Root never needs a password either, which is what makes the cron job and the
timer work.
### The offline update
Debian 13's PackageKit 1.3.1 supports the same offline-update mechanism the Fedora
clients use, so the approach ports directly:
1. `pkcon refresh force` - refresh the package index.
2. `pkcon update --only-download` - download the updates without installing.
3. `pkcon offline-get-prepared` - confirm a payload is ready.
4. `pkcon offline-trigger` - arm the update.
Step 4 creates `/system-update` as a symlink to
`/var/lib/PackageKit/prepared-update`, and systemd's
`packagekit-offline-update.service` (wired into `system-update.target`, shipped by
the `packagekit` package) applies it on the next boot. The desktop is never
sitting on a half-applied transaction.
Step 3 is load-bearing, not ceremony: `offline-get-prepared` exits **4** when
nothing is prepared, and triggering anyway fails and can leave a dangling
`/system-update` symlink, which breaks the next boot. The `if` is what prevents
that.
Two details that differ from the Fedora script:
- `pkcon` exit code **5** means "no packages to update", which is the normal
answer on a patched machine. It is not a failure and is not logged as one.
- The download runs under `systemd-inhibit --what=sleep:idle --mode=block` so the
machine does not suspend mid-download. No `DISPLAY` is needed, which matters
because the timer runs outside any session.
### Who runs it, and when
| | Fedora | Debian |
|---|---|---|
| Citrix repo refresh | cron, 10 min | cron, 10 min |
| offline update | `@reboot` via `/root/auto_update.sh` | `vdi-offline-update.timer`, 6 h + boot, throttled |
On Debian the offline update is a systemd timer (`vdi-offline-update.timer`,
`OnBootSec=15min`, `OnUnitActiveSec=6h`, `Persistent=true`,
`RandomizedDelaySec=15min`) running `/usr/local/sbin/vdi-offline-update`. systemd
owns the scheduling, output goes to the journal, and a failure is visible in
`systemctl status vdi-offline-update.service`. The script also keeps a 6-hour
throttle stamp at `/var/lib/vdi-offline-update.last` so a manual run and the timer
cannot pile up.
`/root/auto_update.sh` is kept for parity with Fedora and simply execs
`/usr/local/sbin/vdi-offline-update`, so there is one implementation rather than
two copies of the `pkcon` sequence.
**Note on scope:** these files are installed by `update_local_repo.py`, not only by
the preseed. That means machines already provisioned before this change pick up
the polkit rule and the timer on their next 10-minute cron run - the same
back-fill approach `configure_kde.py` already uses for the Plasma settings. The
preseed additionally enables the timer directly so a fresh install has offline
updates from the first boot.
### Why not `unattended-upgrades`
Debian's usual answer for automatic updates is `unattended-upgrades`, and it is
the wrong instrument here: it *installs* security updates silently while the user
is working, which is the thing the offline-update flow exists to avoid, and it
does not give a desktop user a no-password update button. It is left uninstalled,
and `pkgsel/update-policy` is `none` in the preseed so the installer does not pull
it in.
Debian still ships `apt-daily.timer` and `apt-daily-upgrade.timer`, which run
regardless. They are not a second updater in practice: `/usr/lib/apt/apt.systemd.daily`
gates every install step on `command -v unattended-upgrade`, so with that package
absent the timer refreshes the package index and stops. Verified on trixie - the
only effect is a cache refresh, not a silent upgrade.
## Building an install ISO
On Fedora, `ks.cfg` is handed to the installer on a second medium or over the
network. Debian's equivalent is to bake `preseed.cfg` into the installation ISO
and point the boot menu at it, so the stick is self-contained.
```
apt-get install xorriso
./debian/make-iso.sh debian-13.7.0-amd64-netinst.iso vdi-debian.iso
```
The script copies the preseed to `/preseed.cfg` on the image and adds this to
every kernel line in every boot menu:
```
auto=true priority=critical preseed/file=/cdrom/preseed.cfg
```
- `auto=true` is an alias for `auto-install/enable`; it delays the locale and
keyboard questions so the preseed can answer them.
- `priority=critical` is an alias for `debconf/priority`; nothing below critical
is asked.
- `preseed/file=/cdrom/preseed.cfg` reads the preseed from the ISO itself. The
`preseed-md5` checksum parameter is deliberately not used: it must match
exactly and breaks the moment the preseed is edited.
The script verifies its own output instead of trusting `xorriso`'s exit status:
the preseed is byte-identical on the image, every kernel line carries the
parameters, both El Torito boot images (BIOS and UEFI) are present, and no file
from the source ISO is missing. It exits non-zero rather than writing an ISO that
would boot to an interactive prompt.
Two things worth knowing if you modify it:
- **Every menu file is patched, not a fixed list.** On a Debian netinst the BIOS
menu is `isolinux/isolinux.cfg`, which contains only `include menu.cfg` and
`default vesamenu.c32`; the entry that actually boots by default is in
`isolinux/gtk.cfg` (`label installgui`, `menu default`). Patching only the
obvious files leaves the default BIOS entry unpatched and the machine still
stops to prompt. The script discovers every `*.cfg` under `/isolinux` and
`/boot/grub` and patches the ones with kernel lines.
- **The image is not extracted and rebuilt.** `xorriso -as mkisofs` over an
extracted tree grows a netinst from 792 MB to 988 MB, because Debian's ISO
shares identical file extents between paths and extraction duplicates them all.
Instead the original session is copied and only the changed files are mapped
over it (`-indev SRC -outdev DST -boot_image any replay -map ...`), which keeps
the deduplication and the boot record intact.
Verified against `debian-13.7.0-amd64-netinst.iso`: 20 of 20 BIOS kernel lines and
20 of 20 UEFI kernel lines patched, all 1010 source files present, preseed
byte-identical, both boot images intact, output 792 MB.
The inventory number is still asked for on the console. The preseed cannot guess
it, and it has to be read from a human.
## configure_kde.py
Writes KWin's `[Libinput][Defaults][Touchpad]` group (so it applies to every
touchpad regardless of vendor), the PowerDevil AC/Battery/LowBattery profiles,
and KScreenLocker. Also installs `/usr/local/bin/vdi-kde-settings` plus an XDG
autostart entry that re-applies the settings inside a running session.
Verified working unchanged on Debian 13 (Plasma 6.3.6): `kwriteconfig6` ships in
`libkf6config-bin`, which the `kde-desktop` task pulls in, and the resulting
`/etc/xdg/{kcminputrc,powerdevilrc,kscreenlockerrc}` are correct. It is idempotent
- a second run changes nothing.
It prefers `sudo -n -u <user>` over `runuser` because on Fedora that also performs
the SELinux context transition needed to reach another user's session bus. On
Debian either works; `runuser` comes from `util-linux`, which is always present,
so the Debian path does not depend on `sudo` being installed. **If you rely on
`sudo` on Debian, install the `sudo` package explicitly** - the `kde-desktop`
task does not pull it in.
## Firefox managed bookmarks
Both families write the same file:
```
/etc/firefox/policies/policies.json (0644, root:root)
```
On Debian this is correct and must not be "fixed". `firefox-esr` 153.6 was traced
with `strace` and it stats exactly one path, `/etc/firefox/policies/policies.json`
- not `/etc/firefox-esr/policies/`, not `/usr/lib/firefox-esr/distribution/`.
Debian's build has `MOZ_SYSTEM_POLICIES` compiled in, which is why it honours the
standard location. Moving the file to `/etc/firefox-esr/policies/` because the
Debian package owns that directory would silently disable managed bookmarks.
## Debian vs Fedora: known differences
These are inherent to preseed vs kickstart, not oversights:
- **Uppercase usernames are impossible via preseed.** `user-setup-udeb` validates
against `[a-z][-a-z0-9_]*$` and re-prompts on failure, which would stall an
unattended install. `VDI-ADMIN` is therefore created with `useradd` in
`late_command`, and `passwd/make-user` is set to false.
- **Disk detection cannot use `lsblk`.** d-i has no `lsblk` and no `openssl`, so
the kickstart's `lsblk -d -o rm` / `openssl passwd -6` have no direct
equivalent. The preseed reads `/sys/block/*/removable` plus `udevadm info`, and
sets passwords with `chpasswd` in the target instead of hashing in the
installer.
- **There is no `chvt`/`openvt` in d-i**, so the kickstart's "switch to TTY3 and
prompt" trick cannot be reproduced. The inventory number is prompted on
`/dev/console`, with a `vdi.inventory=NNNNN` kernel-cmdline override and a
`00000` fallback so an unattended run cannot hang forever.
- **Password hash format.** The kickstart hashes with `openssl passwd -6`
(SHA-512 crypt). `chpasswd` on trixie produces yescrypt by default. Same
outcome, different hash - worth knowing if anything inspects `/etc/shadow`.
- **`git clone` of the internal Gitea server fails soft on Debian.** The Fedora
kickstart aborts the install if the clone fails; the preseed logs and
continues, because the 10-minute cron job retries the work on the next run and
a half-provisioned machine is more useful than no machine.
- **The Citrix install is two steps.** On Fedora `dnf install ICAClient ctxusb`
resolves from the local repo directly. On Debian the packages come from the
local repo that `update_local_repo.py` builds, so `late_command` must run it
first, then `apt-get install -y icaclient ctxusb`, then `apt-get install -f -y`.
## Testing
`debian/test/run-tests.sh` exercises the Debian side on a real Debian 13 machine
and asserts the Fedora side is unregressed. Run it as root on a Debian 13 host or
WSL instance:
```sh
bash debian/test/run-tests.sh
```
It builds a throwaway apt repository from the real Citrix `.deb` files, points a
temporary `sources.list` entry at it, and confirms apt can see and resolve the
packages. It does not touch `/var/local/citrix-repo` and cleans up after itself.
See `debian/test/README.md` for what it covers and what it cannot.
### What the tests do NOT prove
Being explicit, because these are the gaps that matter and it is easy to read a
green summary as more than it is:
- **No real d-i install has been run.** `debian/preseed.cfg` is validated by
`debconf-set-selections` (the real parser), by checking every directive name
against the templates in the actual trixie udebs, and by executing
`late_command` with `/target` redirected to a scratch tree. That proves the
file parses, the directives exist, and the generated scripts are well formed.
It does not prove that an unattended install completes on real hardware - the
disk detection, the partitioner and the console prompt have never run in a
live installer.
- **The generated post-install script is not executed against a real target.**
`/root/vdi-post.sh` writes `/etc/hostname`, `/etc/hosts`, `/etc/crontab` and
`/etc/systemd/system/*` by absolute path, so running it on a build machine
would modify the build machine. It is covered by `bash -n` and by reading the
generated text, plus assertions on the inventory arithmetic it derives.
- **No KDE session has been exercised.** `configure_kde.py` is tested as far as
writing `/etc/xdg/*` and the autostart entry, and its `--session` path is
exercised only against a machine with no session bus (the clean no-op). The
live `busctl` calls against a running KWin/PowerDevil are untested.
- **The Citrix packages are never installed.** The tests prove apt can see them
and that dependency resolution succeeds (`apt-get install --simulate`), not
that `icaclient`'s pre/post-install scripts complete. Those scripts are large
and touch the X11 session; installing them in CI is its own project.
- **The Fedora path is verified by equivalence, not by running it on Fedora.**
The regression test compares the commands the Fedora code issues against
`main`. It does not perform a real `createrepo_c`/`dnf` cycle on a Fedora host.
### Regression testing the Fedora path
A file diff is the wrong instrument for `update_local_repo.py`, because the
Fedora and Debian code now share a file. The meaningful check is behavioural:
run the Fedora publishing path from both `main` and this branch against a stubbed
environment and compare the recorded sequence of operations. They must be
identical - same downloads, same destinations, same `createrepo_c`, `rpm
--import`, `dnf makecache` and `pkcon refresh force` calls, in the same order.
`configure_kde.py`, `local-citrix-repo.repo` and `RPM-GPG-KEY-citrix-local` are
untouched by this branch, and `git diff main -- <those files>` is empty.
### Traps when testing on Debian
- **Purge apt's list cache between cases.** `/var/lib/apt/lists` caches the
index, so a wrong signing key can still appear to work (exit 0, package
visible). Any test that does not purge produces a false pass.
- **`core.autocrlf=true` on a Windows checkout rewrites the worktree to CRLF.**
The repository stores LF, so Linux clients are fine, but copying the worktree
into a Linux test box gives `#!/usr/bin/python3\r` and direct execution fails
with a confusing "No such file or directory". Copy `git show HEAD:file` or strip
the CRs.
- **`strings` is not installed on a stock Debian image.** `strings ... | grep`
with stderr discarded returns empty and looks like a clean negative. Use
`grep -a` on the binary, or install `binutils`.
- **`firefox-esr --headless --dump-dom` hangs under WSL** (RenderCompositorSWGL
cannot map a framebuffer, and it exits 124 on timeout). A tiny DOM from it is
an error page, not a result. Trace the syscalls instead.
+611
View File
@@ -0,0 +1,611 @@
#!/usr/bin/python3
"""Apply the standard KDE Plasma settings used on the VDI clients.
The settings are intentionally model-independent:
* Touchpad settings are written to KWin's global ``[Libinput][Defaults][Touchpad]``
group, so they apply to every touchpad regardless of vendor/product/name.
* PowerDevil is configured for AC, battery and low-battery profiles.
* KScreenLocker is configured not to lock automatically.
The module can be run in two modes:
* as root (default): write the system-wide defaults, update every user in
/home, install the session helper and apply the settings to any user who is
currently logged in;
* ``--session``: run as the logged-in user from the XDG autostart entry. It
applies the settings to the running KWin/PowerDevil/KScreenLocker session.
All operations are idempotent. Only the keys listed below are touched; other
user settings are preserved.
"""
import json
import logging
import os
import pwd
import shutil
import subprocess
import sys
import time
from pathlib import Path
logger = logging.getLogger("vdi-kde-settings")
KWRITE = shutil.which("kwriteconfig6")
KREAD = shutil.which("kreadconfig6")
BUSCTL = shutil.which("busctl")
RUNUSER = shutil.which("runuser")
SUDO = shutil.which("sudo")
SYSTEM_CONFIG_DIR = Path("/etc/xdg")
HELPER_PATH = Path("/usr/local/bin/vdi-kde-settings")
AUTOSTART_DIR = Path("/etc/xdg/autostart")
AUTOSTART_FILE = AUTOSTART_DIR / "vdi-kde-settings.desktop"
LEGACY_TOUCHPAD_CONFIG = Path("/etc/X11/xorg.conf.d/90-libinput-touchpad.conf")
LEGACY_DPMS_SCRIPT = Path("/etc/profile.d/disable-dpms.sh")
LEGACY_SDDM_CONFIG = Path("/etc/sddm.conf.d/10-x11-only.conf")
TOUCHPAD_GROUP = ("Libinput", "Defaults", "Touchpad")
TOUCHPAD_SETTINGS = (
# Match the old Xorg InputClass settings: tapping, natural scrolling,
# disable-while-typing and clickfinger.
("TapToClick", "true", "bool"),
("NaturalScroll", "true", "bool"),
("DisableWhileTyping", "true", "bool"),
("ClickMethod", "2", None), # 2 == clickfinger
)
POWER_PROFILES = ("AC", "Battery", "LowBattery")
POWER_DISPLAY_SETTINGS = (
# "Never" in the PowerDevil KCM.
("DimDisplayWhenIdle", "false", "bool"),
("DimDisplayIdleTimeoutSec", "-1", None),
("TurnOffDisplayWhenIdle", "false", "bool"),
("TurnOffDisplayIdleTimeoutSec", "-1", None),
("LockBeforeTurnOffDisplay", "false", "bool"),
)
POWER_SUSPEND_SETTINGS = (
# No automatic suspend.
("AutoSuspendAction", "0", None), # 0 == NoAction
("AutoSuspendIdleTimeoutSec", "0", None),
)
LOCK_GROUP = ("Daemon",)
LOCK_SETTINGS = (
("Autolock", "false", "bool"),
("Timeout", "0", None),
("LockOnResume", "false", "bool"),
("LockOnStart", "false", "bool"),
)
AUTOSTART_CONTENT = """[Desktop Entry]
Type=Application
Name=VDI KDE Settings
Comment=Apply the standard VDI touchpad, power and screen-lock settings
Exec=/usr/local/bin/vdi-kde-settings --session
Terminal=false
NoDisplay=true
OnlyShowIn=KDE;
X-KDE-autostart-phase=2
"""
def _config_sections():
"""Return [(filename, [((group...), ((key, value, type), ...)), ...])]."""
sections = [("kcminputrc", [(TOUCHPAD_GROUP, TOUCHPAD_SETTINGS)])]
power_sections = []
for profile in POWER_PROFILES:
power_sections.append(((profile, "Display"), POWER_DISPLAY_SETTINGS))
power_sections.append(((profile, "SuspendAndShutdown"), POWER_SUSPEND_SETTINGS))
sections.append(("powerdevilrc", power_sections))
sections.append(("kscreenlockerrc", [(LOCK_GROUP, LOCK_SETTINGS)]))
return sections
def _kconfig_args(command, path, groups, key=None):
args = [command, "--file", str(path)]
for group in groups:
args.extend(["--group", group])
if key is not None:
args.extend(["--key", key])
return args
def _kconfig_get(path, groups, key):
if not KREAD:
return None
try:
result = subprocess.run(
_kconfig_args(KREAD, path, groups, key),
check=False,
capture_output=True,
text=True,
)
except OSError:
return None
if result.returncode != 0:
return None
return result.stdout.strip()
def _kconfig_set(path, groups, key, value, type_name):
if not KWRITE:
logger.warning("kwriteconfig6 is not installed; cannot write %s", path)
return False
args = _kconfig_args(KWRITE, path, groups, key)
if type_name == "bool":
args.extend(["--type", "bool"])
# Values such as "-1" must not be interpreted as command line options.
args.extend(["--", value])
try:
result = subprocess.run(args, check=False, capture_output=True, text=True)
except OSError as error:
logger.warning("Could not run kwriteconfig6: %s", error)
return False
if result.returncode != 0:
logger.warning(
"Could not write %s [%s] %s: %s",
path,
"][".join(groups),
key,
result.stderr.strip(),
)
return False
return True
def _ensure_key(path, groups, key, value, type_name):
"""Write a key only if it differs from the requested value."""
current = _kconfig_get(path, groups, key)
if current == value:
return False
return _kconfig_set(path, groups, key, value, type_name)
def _ensure_config(path, sections, owner=None):
changed = False
for groups, settings in sections:
for key, value, type_name in settings:
if _ensure_key(path, groups, key, value, type_name):
changed = True
if path.exists() and owner is not None:
stat = path.stat()
if stat.st_uid != owner[0] or stat.st_gid != owner[1]:
try:
os.chown(path, owner[0], owner[1])
except OSError as error:
logger.warning("Could not change owner of %s: %s", path, error)
return changed
def ensure_system_configs():
"""Write the system-wide defaults below /etc/xdg."""
try:
SYSTEM_CONFIG_DIR.mkdir(parents=True, exist_ok=True)
except OSError as error:
logger.warning("Could not create %s: %s", SYSTEM_CONFIG_DIR, error)
return
for filename, sections in _config_sections():
path = SYSTEM_CONFIG_DIR / filename
_ensure_config(path, sections, owner=(0, 0))
# kwriteconfig6 creates files with mode 0600; system-wide defaults must
# be readable by the user sessions.
if path.exists():
try:
os.chmod(path, 0o644)
except OSError as error:
logger.warning("Could not change mode of %s: %s", path, error)
def install_helper():
"""Install the session helper and its XDG autostart entry."""
try:
source = Path(__file__).resolve()
target = HELPER_PATH.resolve()
if source != target:
HELPER_PATH.parent.mkdir(parents=True, exist_ok=True)
temporary = HELPER_PATH.with_name(HELPER_PATH.name + ".tmp")
shutil.copy2(source, temporary)
os.chmod(temporary, 0o755)
os.chown(temporary, 0, 0)
os.replace(temporary, HELPER_PATH)
else:
os.chmod(HELPER_PATH, 0o755)
os.chown(HELPER_PATH, 0, 0)
except OSError as error:
logger.warning("Could not install %s: %s", HELPER_PATH, error)
return
try:
AUTOSTART_DIR.mkdir(parents=True, exist_ok=True)
current = AUTOSTART_FILE.read_text() if AUTOSTART_FILE.exists() else None
if current != AUTOSTART_CONTENT:
temporary = AUTOSTART_FILE.with_name(AUTOSTART_FILE.name + ".tmp")
temporary.write_text(AUTOSTART_CONTENT)
os.chmod(temporary, 0o644)
os.chown(temporary, 0, 0)
os.replace(temporary, AUTOSTART_FILE)
if AUTOSTART_FILE.exists():
os.chmod(AUTOSTART_FILE, 0o644)
os.chown(AUTOSTART_FILE, 0, 0)
except OSError as error:
logger.warning("Could not install %s: %s", AUTOSTART_FILE, error)
def ensure_user_configs(user):
"""Write the settings into a user's ~/.config, preserving other keys."""
home = Path(user.pw_dir)
if not home.is_dir():
return False
config_dir = home / ".config"
created = False
if not config_dir.is_dir():
try:
config_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
created = True
except OSError as error:
logger.warning("Could not create %s: %s", config_dir, error)
return False
if created:
try:
os.chown(config_dir, user.pw_uid, user.pw_gid)
except OSError as error:
logger.warning("Could not change owner of %s: %s", config_dir, error)
changed = False
for filename, sections in _config_sections():
path = config_dir / filename
if _ensure_config(path, sections, owner=(user.pw_uid, user.pw_gid)):
changed = True
return changed
def system_users():
"""Yield the regular users whose home is below /home."""
home_root = Path("/home")
if not home_root.is_dir():
return
for entry in sorted(home_root.iterdir()):
if not entry.is_dir():
continue
try:
user = pwd.getpwnam(entry.name)
except KeyError:
continue
if user.pw_uid < 1000:
continue
if Path(user.pw_dir).resolve() != entry.resolve():
continue
if user.pw_shell.endswith(("nologin", "false")):
continue
yield user
def _session_bus(user):
runtime = Path(f"/run/user/{user.pw_uid}")
return runtime, runtime / "bus"
def _session_env(user):
runtime, bus = _session_bus(user)
env = os.environ.copy()
env["XDG_RUNTIME_DIR"] = str(runtime)
env["DBUS_SESSION_BUS_ADDRESS"] = f"unix:path={bus}"
return env
def _busctl(args, env):
if not BUSCTL:
return None
try:
return subprocess.run(
[BUSCTL, "--user"] + args,
env=env,
check=False,
capture_output=True,
text=True,
timeout=15,
)
except (OSError, subprocess.TimeoutExpired):
return None
def _busctl_ok(args, env):
result = _busctl(args, env)
return result is not None and result.returncode == 0
def _kwin_devices(env):
result = _busctl(
[
"--json=short",
"get-property",
"org.kde.KWin",
"/org/kde/KWin/InputDevice",
"org.kde.KWin.InputDeviceManager",
"devicesSysNames",
],
env,
)
if result is None or result.returncode != 0:
return None
try:
return json.loads(result.stdout).get("data", [])
except (json.JSONDecodeError, AttributeError):
return None
def _kwin_property(env, path, name):
result = _busctl(
[
"--json=short",
"get-property",
"org.kde.KWin",
path,
"org.kde.KWin.InputDevice",
name,
],
env,
)
if result is None or result.returncode != 0:
return None
try:
return json.loads(result.stdout).get("data")
except (json.JSONDecodeError, AttributeError):
return None
def _set_kwin_bool(env, path, name, value=True):
current = _kwin_property(env, path, name)
if current is value:
return False
result = _busctl(
[
"set-property",
"org.kde.KWin",
path,
"org.kde.KWin.InputDevice",
name,
"b",
"true" if value else "false",
],
env,
)
if result is None or result.returncode != 0:
return False
return True
def _apply_touchpad(env, sysname):
path = f"/org/kde/KWin/InputDevice/{sysname}"
if _kwin_property(env, path, "touchpad") is not True:
return
name = _kwin_property(env, path, "name") or sysname
changed = False
for prop, support_prop in (
("tapToClick", None),
("naturalScroll", "supportsNaturalScroll"),
("disableWhileTyping", "supportsDisableWhileTyping"),
("clickMethodClickfinger", "supportsClickMethodClickfinger"),
):
if support_prop is not None and _kwin_property(env, path, support_prop) is False:
continue
if _set_kwin_bool(env, path, prop):
changed = True
if changed:
logger.info("Applied touchpad settings to %s (%s)", name, sysname)
def _emit_kwin_reload(env):
_busctl_ok(
[
"emit",
"/KGlobalSettings",
"org.kde.KGlobalSettings",
"notifyChange",
"ii",
"3",
"0",
],
env,
)
def apply_session():
"""Apply settings to the current graphical session (run as the user)."""
try:
user = pwd.getpwuid(os.getuid())
except KeyError:
logger.error("Could not determine the current user")
return 1
try:
ensure_user_configs(user)
except Exception:
logger.exception("Could not update the user configuration")
env = _session_env(user)
_runtime, bus = _session_bus(user)
if not bus.exists():
logger.info("No session bus for %s; skipping live KDE settings", user.pw_name)
return 0
# KWin and PowerDevil may still be starting when the autostart entry runs.
devices = None
deadline = time.monotonic() + 15
while time.monotonic() < deadline:
devices = _kwin_devices(env)
if devices is not None:
break
time.sleep(0.5)
if devices is None:
logger.warning("KWin input devices are not available yet")
else:
# Let KWin re-read kcminputrc, then force the values on every touchpad
# so that stale per-device entries from older versions are corrected.
_emit_kwin_reload(env)
for sysname in devices:
_apply_touchpad(env, sysname)
_busctl_ok(
[
"call",
"org.kde.Solid.PowerManagement",
"/org/kde/Solid/PowerManagement",
"org.kde.Solid.PowerManagement",
"refreshStatus",
],
env,
)
_busctl_ok(
[
"call",
"org.kde.screensaver",
"/ScreenSaver",
"org.kde.screensaver",
"configure",
],
env,
)
return 0
def _run_session_helper(user):
if not HELPER_PATH.exists():
return
# Prefer sudo: it also performs the SELinux context transition to the
# target user, which is needed to connect to that user's session bus from
# a root cron job on Fedora.
if SUDO:
# -n: never prompt. Root does not need a password; this only prevents a
# stuck cron job if sudo is misconfigured.
runner = [SUDO, "-n", "-u", user.pw_name, "--"]
elif RUNUSER:
runner = [RUNUSER, "-u", user.pw_name, "--"]
else:
logger.warning("Neither sudo nor runuser is available; cannot run session helper")
return
runtime, _bus = _session_bus(user)
command = runner + [
"/usr/bin/env",
f"HOME={user.pw_dir}",
f"XDG_RUNTIME_DIR={runtime}",
f"DBUS_SESSION_BUS_ADDRESS=unix:path={runtime}/bus",
"PATH=/usr/local/bin:/usr/bin:/bin",
str(HELPER_PATH),
"--session",
]
try:
result = subprocess.run(
command, check=False, capture_output=True, text=True, timeout=45
)
except (OSError, subprocess.TimeoutExpired) as error:
logger.warning("Could not apply settings for %s: %s", user.pw_name, error)
return
if result.returncode != 0:
logger.warning(
"Session helper failed for %s: %s",
user.pw_name,
result.stderr.strip(),
)
def _remove_legacy_file(path, description):
if not path.exists() and not path.is_symlink():
return
try:
path.unlink()
logger.info("Removed legacy %s (%s)", description, path)
except OSError as error:
logger.warning("Could not remove %s: %s", path, error)
def cleanup_legacy_config():
"""Remove the old X11/SDDM-only provisioning files."""
_remove_legacy_file(LEGACY_TOUCHPAD_CONFIG, "Xorg touchpad configuration")
_remove_legacy_file(LEGACY_DPMS_SCRIPT, "xset DPMS script")
_remove_legacy_file(LEGACY_SDDM_CONFIG, "X11-only SDDM configuration")
skel_link = Path("/etc/skel/.config/autostart-scripts/disable-dpms.sh")
_remove_legacy_file(skel_link, "xset autostart symlink")
# Older versions of the provisioning script disabled the Wayland session
# by renaming its desktop file.
disabled = Path("/usr/share/wayland-sessions/plasmawayland.desktop.disabled")
current = Path("/usr/share/wayland-sessions/plasmawayland.desktop")
plasma = Path("/usr/share/wayland-sessions/plasma.desktop")
if disabled.exists():
try:
if current.exists() or plasma.exists():
disabled.unlink()
else:
disabled.rename(current)
logger.info("Restored the Wayland session entry")
except OSError as error:
logger.warning("Could not restore the Wayland session entry: %s", error)
def cleanup_user_legacy(user):
link = Path(user.pw_dir) / ".config/autostart-scripts/disable-dpms.sh"
if not link.is_symlink():
return
try:
target = os.readlink(link)
except OSError:
return
if target == str(LEGACY_DPMS_SCRIPT) or "disable-dpms.sh" in target:
_remove_legacy_file(link, "user xset autostart symlink")
def apply_all():
"""Root entry point: write defaults and update all users."""
if os.geteuid() != 0:
logger.error("This mode must be run as root")
return 1
cleanup_legacy_config()
install_helper()
ensure_system_configs()
for user in system_users():
try:
ensure_user_configs(user)
except Exception:
logger.exception("Could not update configuration for %s", user.pw_name)
try:
cleanup_user_legacy(user)
except Exception:
logger.exception("Could not clean up legacy files for %s", user.pw_name)
_runtime, bus = _session_bus(user)
if bus.exists():
_run_session_helper(user)
return 0
def main():
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s",
)
if "--session" in sys.argv[1:]:
return apply_session()
return apply_all()
if __name__ == "__main__":
sys.exit(main())
Vendored Executable
+204
View File
@@ -0,0 +1,204 @@
#!/bin/bash
# Build a Debian installation ISO that runs this preseed unattended.
#
# This is the Debian equivalent of putting ks.cfg on the Fedora ISO: the preseed
# is baked into the image and the boot menu is edited to load it, so the machine
# installs with no questions and no extra medium.
#
# Usage:
# ./make-iso.sh /path/to/debian-13.x.x-amd64-netinst.iso [output.iso]
#
# Requirements: xorriso only.
# apt-get install xorriso
#
# The ISO is rebuilt, not modified in place: the source ISO is never touched.
#
# WHY THE FILES ARE MAPPED ONTO THE ORIGINAL IMAGE INSTEAD OF EXTRACTING IT
#
# The obvious implementation - extract the whole tree, edit, rebuild with
# `xorriso -as mkisofs` - works but grows the image by ~186 MB on a netinst
# (792 MB -> 988 MB), because Debian's ISO shares identical file extents between
# paths and extracting to a normal filesystem duplicates all of them.
#
# `xorriso -indev SRC -outdev DST -boot_image any replay -map ...` instead copies
# the original session and overwrites only the files named in -map, so the
# deduplication and the boot record survive untouched. Verified on
# debian-13.7.0-amd64-netinst.iso: output 792002560 bytes vs source 792723456,
# all 1010 source files present, the four payload files byte-identical except
# for the boot-info table, and both El Torito images (BIOS and UEFI) intact.
set -euo pipefail
SRC_ISO=${1:-}
OUT_ISO=${2:-}
HERE=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
PRESEED="$HERE/preseed.cfg"
die() { printf 'make-iso: %s\n' "$*" >&2; exit 1; }
note() { printf ' %s\n' "$*"; }
[ -n "$SRC_ISO" ] || die "usage: $0 <debian-netinst.iso> [output.iso]
the ISO is the one you would otherwise boot by hand, e.g.
debian-13.7.0-amd64-netinst.iso"
[ -f "$SRC_ISO" ] || die "no such ISO: $SRC_ISO"
[ -f "$PRESEED" ] || die "preseed.cfg not found next to this script: $PRESEED"
command -v xorriso >/dev/null 2>&1 || die "xorriso is required (apt-get install xorriso)"
if [ -z "$OUT_ISO" ]; then
OUT_ISO="${SRC_ISO%.iso}-vdi.iso"
fi
[ "$OUT_ISO" != "$SRC_ISO" ] || die "refusing to overwrite the source ISO"
if [ -e "$OUT_ISO" ]; then
# Overwriting an existing image is destructive and never what is wanted by
# accident; the caller can remove it deliberately.
die "output already exists: $OUT_ISO (remove it first)"
fi
WORK=$(mktemp -d "${TMPDIR:-/tmp}/make-iso.XXXXXX")
# shellcheck disable=SC2064
trap "rm -rf '$WORK'" EXIT
# ---------------------------------------------------------------------------
# 1. Find every boot menu file on the ISO.
#
# Discovered rather than hardcoded, because a fixed list gets this wrong in a way
# that is easy to miss: on Debian's netinst the BIOS menu is isolinux.cfg, which
# is only "include menu.cfg" and "default vesamenu.c32"; the actual default entry
# is defined in gtk.cfg (label installgui, "menu default"). Patching only the
# obvious files leaves the default BIOS entry unpatched, so the machine still
# stops and prompts - exactly the failure this script exists to prevent.
# So: every .cfg under isolinux/ and boot/grub/ that contains a kernel line gets
# the parameters.
# ---------------------------------------------------------------------------
MENUS=$(
for dir in /isolinux /boot/grub; do
xorriso -indev "$SRC_ISO" -find "$dir" -name '*.cfg' 2>/dev/null
done | tr -d "'" | grep -v '^$' | sort -u
)
[ -n "$MENUS" ] || die "no .cfg files found under /isolinux or /boot/grub in $SRC_ISO
- is this a Debian netinst ISO?"
# ---------------------------------------------------------------------------
# 2. Patch each menu.
#
# The parameters, per the Debian installation guide (appendix B.2.1):
# auto=true alias for auto-install/enable; delays the locale and
# keyboard questions so the preseed can answer them
# priority=critical alias for debconf/priority; stops anything below
# critical from being asked
# preseed/file= read the preseed from the ISO itself
#
# The checksum parameter is deliberately omitted: it must be an md5 and must
# match exactly, so it breaks the moment the preseed is edited.
# ---------------------------------------------------------------------------
PARAMS='auto=true priority=critical preseed/file=/cdrom/preseed.cfg'
MAP_ARGS=()
for menu in $MENUS; do
local_name="$WORK/$(echo "$menu" | tr '/' '_')"
xorriso -osirrox on -indev "$SRC_ISO" -extract "/$menu" "$local_name" 2>/dev/null \
|| die "could not extract /$menu from the ISO"
chmod u+w "$local_name"
before=$(grep -cF 'preseed/file=' "$local_name" || true)
# Some menus are stubs: Debian's /boot/grub/x86_64-efi/grub.cfg is a single
# line, "source /boot/grub/grub.cfg", with no kernel entries of its own. It
# inherits the patched entries through the source, so there is nothing to
# edit and requiring a change there would be wrong. Count the real kernel
# lines first and skip a menu that has none.
kernels=$(grep -cE '^[[:space:]]*(append|linux)[[:space:]]' "$local_name" || true)
if [ "$kernels" -eq 0 ]; then
note "/$menu: no kernel entries of its own (stub), left alone"
continue
fi
# Two quoting traps, both found by running this rather than by reading it:
# * '@' is the delimiter because the pattern uses '|' for the
# append/linux alternation, so '|' cannot also delimit the s/// command;
# * the end-of-pattern '$' must be written '\$'. Inside double quotes a
# bare '$@' expands to the script's positional parameters, which turns
# the expression into garbage and makes sed report "unterminated s".
# The /^[[:space:]]*#/! guard keeps comment lines out of the rewrite.
sed -i -E \
-e "/^[[:space:]]*#/! s@^([[:space:]]*(append|linux)[[:space:]].*)\$@\1 ${PARAMS}@" \
"$local_name"
after=$(grep -cF 'preseed/file=' "$local_name" || true)
if [ "$after" -le "$before" ]; then
die "patching /$menu changed nothing - the menu layout is not what this script expects"
fi
note "/$menu: $after installer entr(y|ies) now pass the preseed"
MAP_ARGS+=(-map "$local_name" "/$menu")
done
# ---------------------------------------------------------------------------
# 3. Rebuild by replaying the original session and overwriting only our files.
# ---------------------------------------------------------------------------
note "building $OUT_ISO"
xorriso -indev "$SRC_ISO" -outdev "$OUT_ISO" \
-boot_image any replay \
-map "$PRESEED" /preseed.cfg \
"${MAP_ARGS[@]}" \
2>&1 | grep -iE "xorriso : FAILURE|libisofs: ERROR|completed successfully" || true
[ -s "$OUT_ISO" ] || die "xorriso did not produce $OUT_ISO"
# ---------------------------------------------------------------------------
# 4. Verify rather than trust the exit status.
#
# xorriso can report success having silently skipped a -map, and an ISO that
# boots to an interactive prompt is worse than no ISO at all. These checks are
# the ones that would actually catch that.
# ---------------------------------------------------------------------------
note "verifying the result"
# 4a. The preseed must be on the image, byte-identical to the source.
xorriso -osirrox on -indev "$OUT_ISO" -extract /preseed.cfg "$WORK/check.cfg" 2>/dev/null \
|| die "the preseed is not on the output ISO"
cmp -s "$WORK/check.cfg" "$PRESEED" \
|| die "the preseed on the ISO differs from $PRESEED"
note "preseed present and byte-identical"
# 4b. Every menu that has kernel entries must carry the parameter. A stub
# menu has none and inherits them through its source line.
for menu in $MENUS; do
local_name="$WORK/verify_$(echo "$menu" | tr '/' '_')"
xorriso -osirrox on -indev "$OUT_ISO" -extract "/$menu" "$local_name" 2>/dev/null \
|| die "cannot read /$menu back from the output ISO"
kernels=$(grep -cE '^[[:space:]]*(append|linux)[[:space:]]' "$local_name" || true)
[ "$kernels" -eq 0 ] && continue
grep -qF 'preseed/file=/cdrom/preseed.cfg' "$local_name" \
|| die "/$menu on the output ISO does not pass the preseed parameter"
done
note "boot menus on the output ISO pass: $PARAMS"
# 4c. Both El Torito images must still be there, or the stick will not boot on
# one of the two firmware types.
TORITO=$(xorriso -indev "$OUT_ISO" -report_el_torito plain 2>&1)
printf '%s' "$TORITO" | grep -q 'El Torito' || die "the output ISO has no El Torito boot record"
BIOS=0; UEFI=0
printf '%s' "$TORITO" | grep -q 'BIOS' && BIOS=1
printf '%s' "$TORITO" | grep -q 'UEFI' && UEFI=1
if [ "$BIOS" -eq 1 ] && [ "$UEFI" -eq 1 ]; then
note "boot record intact (BIOS and UEFI images present)"
else
# Not fatal if the source never had one of them, but say so plainly.
note "WARNING: only one firmware type is bootable (BIOS=$BIOS UEFI=$UEFI);"
note " check the source ISO - this is inherited, not caused here"
fi
# 4d. Nothing may be missing relative to the source.
xorriso -indev "$SRC_ISO" -find / -type f -exec lsdl 2>/dev/null | awk '{print $NF}' | sort > "$WORK/src.list"
xorriso -indev "$OUT_ISO" -find / -type f -exec lsdl 2>/dev/null | awk '{print $NF}' | sort > "$WORK/out.list"
MISSING=$(comm -23 "$WORK/src.list" "$WORK/out.list" | wc -l)
[ "$MISSING" -eq 0 ] || die "$MISSING file(s) from the source ISO are missing in the output"
note "all $(wc -l < "$WORK/src.list") source files present"
note "wrote $OUT_ISO ($(du -h "$OUT_ISO" | cut -f1))"
cat <<EOF
Done. Write it to a stick with:
dd if=$(basename "$OUT_ISO") of=/dev/sdX bs=4M status=progress conv=fsync
The installer will now run this preseed with no questions. It still asks for the
inventory number - the preseed cannot guess it - which happens on the console
before partitioning.
EOF
+564
View File
@@ -0,0 +1,564 @@
#_preseed_V1
#
# Debian 13 "trixie" preseed - the port of the Fedora kickstart at
# ../../ks.cfg (one directory above this git repo).
#
# This file is the Debian equivalent of ks.cfg. Every block below names the
# kickstart directive it corresponds to, so a maintainer of the Fedora path can
# diff the two side by side. Where Debian's installer (d-i) cannot do what the
# kickstart does, the block says so and explains what is done instead - see
# "GAPS" at the end for the consolidated list.
#
# Directive existence: every "d-i <question>" line below was checked against the
# real template files shipped in the trixie d-i udebs (preseed-common,
# partman-*, netcfg, user-setup-udeb, localechooser, tzsetup, console-setup,
# clock-setup, pkgsel, base-installer, apt-setup, grub-installer, finish-install,
# hw-detect, di-utils) plus tasksel/keyboard-configuration from the main archive.
# No directive here is guessed.
#
# Validated with: debconf-set-selections < preseed.cfg (see debian/README)
# ---------------------------------------------------------------------------
# Installation source
# ---------------------------------------------------------------------------
# ks.cfg:1-2 url --mirrorlist=https://mirrors.fedoraproject.org/...fedora-44
# Debian has no metalink; the canonical archive is the equivalent. Protocol,
# host and directory are preseeded individually so the mirror question is never
# asked and no network round-trip to the mirror list happens.
d-i mirror/country string DE
d-i mirror/protocol select http
d-i mirror/http/hostname string deb.debian.org
d-i mirror/http/directory string /debian
d-i mirror/http/proxy string
d-i mirror/suite string trixie
d-i mirror/codename string trixie
# ---------------------------------------------------------------------------
# Language, keyboard, timezone
# ---------------------------------------------------------------------------
# ks.cfg:5 lang de_DE.UTF-8
# language + country are set alongside locale so localechooser never asks: the
# shortlist question is skipped when the locale is already preseeded, and the
# two extra keys make the country/language selection deterministic too.
d-i debian-installer/language string de
d-i debian-installer/country string DE
d-i debian-installer/locale string de_DE.UTF-8
# ks.cfg:5 asks for German only; do not pull in a second locale.
d-i localechooser/supported-locales multiselect de_DE.UTF-8
# ks.cfg:6 keyboard de
# On trixie there is no "debian-installer/keymap" template any more - it survives
# only as an alias handled by env-preseed, which maps "keymap" onto
# keyboard-configuration/xkb-keymap. The real question is the one below, and
# layoutcode is set as well because that is what ends up in
# /etc/default/keyboard as XKBLAYOUT.
d-i keyboard-configuration/xkb-keymap select de
d-i keyboard-configuration/layoutcode string de
d-i keyboard-configuration/modelcode string pc105
d-i keyboard-configuration/variantcode string
# ks.cfg:9 timezone Europe/Berlin
d-i time/zone string Europe/Berlin
# Fedora's installer sets the hardware clock to UTC by default and so does d-i;
# stated explicitly rather than relied on.
d-i clock-setup/utc boolean true
d-i clock-setup/ntp boolean true
d-i clock-setup/ntp-server string deb.debian.org
# ---------------------------------------------------------------------------
# Accounts - root
# ---------------------------------------------------------------------------
# ks.cfg:12 rootpw <sha512 hash> --iscrypted
# Same hash, byte for byte. Type is "password" and the value is the crypt(3)
# string, which is exactly what d-i's user-setup-apply feeds to usermod
# --password, so no re-hashing happens anywhere.
d-i passwd/root-password-crypted password $6$3EpVOhxlL/EVU/8f$Z.M5x/x5OdzBFW2C0IoNo5KCsLURBJZnp1BgcMWFz8gsjEPSgAlBKEs7CgZnRAGjbrEzgvUCEydmjtZYvUraJ/
# ks.cfg sets a root password, which on Fedora implies root may log in. d-i
# defaults to locking root when a non-root user exists; say so explicitly.
d-i passwd/root-login boolean true
# ---------------------------------------------------------------------------
# Accounts - users
# ---------------------------------------------------------------------------
# ks.cfg:15 user --name=VDI-ADMIN --password <same hash> --iscrypted --groups=wheel
#
# GAP 1 (important). This CANNOT be expressed as a preseed user.
# user-setup-udeb validates the username with
# LC_ALL=C expr "$USER" : '[a-z][-a-z0-9_]*$'
# (read out of user-setup-udeb 1.107, ./usr/bin/user-setup-ask, state 6).
# "VDI-ADMIN" is uppercase, so it fails validation, and on failure the state
# machine loops back and asks the question again interactively - which would
# hang an unattended install. So the built-in user creation is disabled here and
# BOTH users are created in preseed/late_command instead (see vdi-post.sh
# below), using useradd, which does accept it. Verified on Debian 13:
# useradd -m -G sudo -c 'VDI-00000' VDI-ADMIN -> rc=0
# id VDI-ADMIN -> uid=1000(VDI-ADMIN) groups=...,27(sudo)
# Fedora's "wheel" group is Debian's "sudo" group.
d-i passwd/make-user boolean false
# The kickstart's second user (ks.cfg:85, generated in %pre) is vdi<NNNNN>.
# That name would pass user-setup's validation, but the password is derived from
# the inventory number and the number is only known at run time, so both users
# are created together in late_command for consistency.
d-i passwd/username string vdi00000
d-i passwd/user-fullname string VDI-00000
# ---------------------------------------------------------------------------
# Network
# ---------------------------------------------------------------------------
# ks.cfg:84 network --bootproto=dhcp --hostname=$HOSTNAME --activate
# The hostname is not a constant: it is EXTVDIL<NNNNN> and is derived from the
# operator's answer in preseed/early_command. The value below is only the
# placeholder that is replaced there; "netcfg/hostname" is the documented
# "for internal use; can be preseeded" question that overrides whatever DHCP
# supplies, which is what --hostname does on Fedora.
d-i netcfg/enable boolean true
d-i netcfg/choose_interface select auto
d-i netcfg/get_hostname string EXTVDIL00000
d-i netcfg/hostname string EXTVDIL00000
# The kickstart does not set a domain and the VDI machines are not in one.
d-i netcfg/get_domain string
d-i netcfg/dhcp_timeout string 60
d-i netcfg/use_autoconfig boolean true
# ---------------------------------------------------------------------------
# Disk partitioning
# ---------------------------------------------------------------------------
# ks.cfg:53-56 (generated in %pre)
# ignoredisk --only-use=$DISK_NAME
# zerombr
# clearpart --all --initlabel
# autopart --fstype=ext4
#
# Mapping:
# ignoredisk --only-use -> partman-auto/disk (restricts the automatic
# partitioner to exactly one disk)
# zerombr + --initlabel -> partman-partitioning/default_label gpt
# (relabels the disk, discarding the old table)
# clearpart --all -> partman-auto/method regular, which builds a fresh
# table from a recipe instead of reusing anything
# autopart --fstype -> partman/default_filesystem ext4
#
# GAP 2 - WHEN the disk is detected, and why it is not preseed/early_command.
# The kickstart detects the disk in %pre, before anaconda partitions. In d-i the
# equivalent-looking hook, preseed/early_command, runs from
# env-preseed's S33preseed_early_command, which is before partman has probed the
# disks - Debian's own example preseed says so explicitly ("disks ... may not be
# visible when preseed/early_command runs") and names the correct hook:
# d-i partman/early_command \
# string debconf-set partman-auto/disk "$(list-devices disk | head -n1)"
# partman-base runs that hook from ./lib/partman/init.d/01early_command, i.e.
# inside partman, with the disk list populated. So the detection lives in
# partman/early_command below.
#
# GAP 3 - the kickstart's two disk tools do not exist in d-i at all.
# `lsblk -d -o rm` and `openssl passwd -6` are both absent from every trixie
# udeb (checked by unpacking them all; d-i has no lsblk, no openssl, no
# python3, no chvt, no passwd binary). The detection below therefore reads
# /sys/block/*/removable and uses udevadm (present, from udev-udeb) for the USB
# test, and nothing is hashed in d-i - the inventory password is set with
# chpasswd in the installed system, which hashes it there.
#
# partman-auto/disk is deliberately NOT set statically: if detection ever fails
# the installer must fall back to the interactive partitioner rather than wipe a
# disk that merely matched a hard-coded default. Detection failure is therefore
# safe-by-construction: nothing is partitioned until the operator confirms.
d-i partman-auto/method string regular
d-i partman-auto/choose_recipe select atomic
d-i partman/default_filesystem string ext4
d-i partman-partitioning/default_label string gpt
d-i partman/alignment select optimal
# Wipe any pre-existing LVM/MD metadata, the way zerombr/clearpart --all do.
d-i partman-lvm/device_remove_lvm boolean true
d-i partman-md/device_remove_md boolean true
# No "are you sure?" / "write changes?" dialogs - the kickstart is unattended.
d-i partman/confirm boolean true
d-i partman/confirm_nooverwrite boolean true
# Detects the single internal disk, skipping USB and removable devices, then
# hands it to partman. Runs inside partman, after the disks are visible.
# This is the replacement for ks.cfg:18-60.
#
# The kickstart only ever looked at /dev/nvme[0-9]n[0-9] (so its own comment
# about "SATA, NVMe, eMMC" was never true). This scans every block device,
# prefers NVMe as the kickstart intended, and accepts SATA/eMMC/virtio as well.
d-i partman/early_command string \
disk=""; \
for d in /sys/block/*; do \
n=$(basename "$d"); \
case "$n" in loop*|ram*|zram*|sr*|dm-*|md*|fd*) continue ;; esac; \
[ -b "/dev/$n" ] || continue; \
[ "$(cat "$d/removable" 2>/dev/null || echo 1)" = 0 ] || continue; \
if udevadm info -q property -n "/dev/$n" 2>/dev/null | grep -q "^ID_BUS=usb"; then continue; fi; \
case "$n" in nvme*) disk="/dev/$n"; break ;; *) [ -n "$disk" ] || disk="/dev/$n" ;; esac; \
done; \
if [ -n "$disk" ]; then \
debconf-set partman-auto/disk "$disk"; \
debconf-set grub-installer/bootdev "$disk"; \
echo "VDI: internal disk $disk" >> /var/log/vdi-preseed.log; \
else \
echo "VDI: no internal disk found - falling back to the interactive partitioner" >> /var/log/vdi-preseed.log; \
fi
# ---------------------------------------------------------------------------
# Inventory number (ks.cfg:18-93, the whole %pre section)
# ---------------------------------------------------------------------------
# The kickstart writes its results into /tmp/ks_dynamic.cfg and %includes it.
# d-i has no %include; the same effect is achieved by writing the derived values
# straight into debconf with debconf-set (from di-utils), which is the sanctioned
# idiom - Debian's example preseed uses it for partman-auto/disk.
#
# GAP 4 - the prompt itself. The kickstart switches to TTY3 with `chvt 3` and
# reads from /dev/tty3. d-i ships neither chvt nor openvt (confirmed absent from
# every udeb), and preseed_command runs the hook through `log-output`, which
# sends stdout to the log rather than to the screen. So the prompt is written to
# and read from /dev/console directly, which is the console the operator is
# actually looking at.
#
# Two safety valves the kickstart does not have, because an unattended run must
# not hang forever on a `read` that nobody answers:
# * vdi.inventory=NNNNN on the kernel command line skips the prompt entirely;
# * otherwise the prompt waits 120 s and then uses the kickstart's default,
# 00000.
# Both are documented in debian/README.
d-i preseed/early_command string \
inv=""; \
for a in $(cat /proc/cmdline); do case "$a" in vdi.inventory=*) inv="${a#vdi.inventory=}" ;; esac; done; \
if [ -z "$inv" ] && [ -c /dev/console ]; then \
printf "\n\nEnter the 5-digit inventory number for this device (default 00000): " > /dev/console; \
IFS= read -r -t 120 inv < /dev/console || true; \
fi; \
[ -n "$inv" ] || inv=00000; \
inv=$(printf "%s" "$inv" | tr -cd "0-9" | cut -c1-5); \
[ -n "$inv" ] || inv=00000; \
while [ ${#inv} -lt 5 ]; do inv="0${inv}"; done; \
printf "%s" "$inv" > /tmp/vdi.inventory; \
debconf-set netcfg/hostname "EXTVDIL${inv}"; \
debconf-set netcfg/get_hostname "EXTVDIL${inv}"; \
debconf-set passwd/username "vdi${inv}"; \
debconf-set passwd/user-fullname "VDI-${inv}"; \
echo "VDI: inventory=${inv}" >> /var/log/vdi-preseed.log
#
# ks.cfg:73 INVENTORY_NUM=$(printf "%05d" ${INVENTORY_NUM:0:5})
# Reproduced, but with a zero-padding loop instead of printf: `printf "%05d"`
# treats the value as octal, so the kickstart's own line fails on an inventory
# number containing an 8 or 9 (e.g. 00019). The loop gives the same result and
# cannot fail.
#
# Derived values, all from ks.cfg:77-80:
# hostname EXTVDIL<NNNNN> -> netcfg/hostname above
# username vdi<NNNNN> -> passwd/username above
# full name VDI-<NNNNN> -> passwd/user-fullname above
# password pwVDI#<NNNNN> -> set with chpasswd in late_command
# (d-i has no openssl, see GAP 3)
# ---------------------------------------------------------------------------
# Boot loader
# ---------------------------------------------------------------------------
# ks.cfg:96 bootloader --location=mbr
# The device is set from the detected disk in partman/early_command above, which
# is the same disk the partitioning is restricted to. "default" would also work
# but naming the disk is closer to --location=mbr and cannot pick the wrong one.
d-i grub-installer/only_debian boolean true
d-i grub-installer/with_other_os boolean false
# ---------------------------------------------------------------------------
# Package selection
# ---------------------------------------------------------------------------
# ks.cfg:99-105
# @^kde-desktop-environment
# createrepo_c
# python3-pip
# firefox
# git
#
# @^kde-desktop-environment -> the "kde-desktop" task (verified in
# tasksel-data 3.81: Task: kde-desktop, Parent: desktop). "standard" is the
# Debian equivalent of the base group anaconda always installs.
# firefox -> firefox-esr (trixie has no package called
# "firefox"; verified in the trixie Packages index)
# createrepo_c -> apt-utils, which is what provides apt-ftparchive,
# the tool that builds a flat apt repository. There is no createrepo on
# Debian and no createrepo_c either.
# python3-pip -> DROPPED. ks.cfg:143 installs pip only in order to run
# `pip install tqdm`, and that one use is served by python3-tqdm from apt (GAP 5).
# Debian 13 marks /usr/lib/python3/dist-packages EXTERNALLY-MANAGED (PEP 668), so
# any user who tries `pip install <anything>` after install gets
# "error: externally-managed-environment" and has to reach for
# --break-system-packages. Measured on trixie, not assumed: `pip3 install
# requests` is blocked AND so is `pip3 install --user six`. So installing
# python3-pip would not make pip usable - it only changes the error from
# "command not found" to "externally-managed-environment". It adds no capability
# that this image would otherwise have. This is a deliberate difference from the
# Fedora kickstart. The supported route is a venv, which is why python3-venv is
# installed below instead.
tasksel tasksel/first multiselect standard, kde-desktop
# Package list notes, one per entry that is not a straight rename:
# python3 - update_local_repo.py is python3 and the cron job runs it.
# A bare trixie install has no python3, and without it the
# cron job fails every 10 minutes with only a log line.
# apt-utils - provides apt-ftparchive, which update_local_repo.py calls
# to build the local Citrix repo (the createrepo_c slot).
# python3-tqdm - the tqdm dependency, from apt instead of pip (GAP 5).
# python3-venv - the replacement for the dropped python3-pip: a venv is the
# only way to install a third-party Python package on trixie.
# `python3 -m venv` needs this package to create a working
# pip inside the venv; without it a user has no route at all.
# Verified on trixie: python3 -m venv gives pip 25.1.1 and
# `venv/bin/pip install six` succeeds (EXTERNALLY-MANAGED does
# not apply inside a venv). It pulls python3-pip-whl, which is
# pip bundled as a wheel for venv use - that is NOT python3-pip
# and does not put a system pip3 on PATH.
# wget - the teamviewer key download in the post-install script
# uses wget (present in trixie as 1.25.0-2).
# sudo - needed for the "sudo" group. The kde-desktop task does not
# pull sudo in, and `useradd -G sudo` would otherwise
# succeed with a warning and leave VDI-ADMIN unable to sudo.
# cron - the kickstart appends to /etc/crontab and restarts crond;
# Debian does not install cron by default.
# packagekit-tools - provides pkcon. /root/auto_update.sh no longer calls pkcon
# directly (it delegates to /usr/local/sbin/vdi-offline-update);
# that helper, which update_local_repo.py installs, is what
# runs pkcon refresh/update and the offline prepare/trigger.
# iputils-ping - the @reboot cron line waits on `ping google.com`.
d-i pkgsel/include string git python3 python3-tqdm python3-venv firefox-esr apt-utils cron sudo ca-certificates wget iputils-ping packagekit-tools systemd
d-i pkgsel/run_tasksel boolean true
# ks.cfg does not upgrade the system during install, and does not enable
# automatic security updates (it runs its own pkcon-based updater instead).
d-i pkgsel/upgrade select none
d-i pkgsel/update-policy select none
d-i pkgsel/updatedb boolean false
d-i base-installer/install-recommends boolean true
#
# GAP 5 - tqdm. ks.cfg:143 does `pip install tqdm`, because Fedora ships pip and
# lets it write into /usr. Debian 13 does not: pip3 is not installed by default,
# and /usr/lib/python3.13/EXTERNALLY-MANAGED is present (PEP 668), so a
# system-wide pip install is refused even after installing pip. The Debian way,
# and what this file does, is the distribution package python3-tqdm
# (4.67.1-5 on trixie). `pip install --break-system-packages` is deliberately
# not used, and because the only thing the kickstart wanted pip for was tqdm,
# python3-pip itself is not installed either - see the package-selection note
# above. Measured on trixie: `pip3 install X` and `pip3 install --user X` are both
# refused with externally-managed-environment, so pip would have been dead weight.
# python3-venv is installed in its place, which is the supported route.
#
# GAP 6 - `pkcon` is used by the auto-update script below. On Fedora it comes
# with the desktop; on Debian it is in packagekit-tools, which is therefore in
# the list above. iputils-ping is there because the kickstart's @reboot cron
# line waits on `ping google.com` and Debian does not install ping by default.
# ---------------------------------------------------------------------------
# Remainder of the installer, made non-interactive
# ---------------------------------------------------------------------------
# There is no kickstart equivalent for these; they exist so that nothing else
# stops and waits for a human.
d-i hw-detect/load_firmware boolean false
d-i apt-setup/services-select multiselect security, updates
d-i apt-setup/enable-source-repositories boolean false
d-i finish-install/keep-consoles boolean false
d-i cdrom-detect/eject boolean false
# ---------------------------------------------------------------------------
# %post (ks.cfg:108-221)
# ---------------------------------------------------------------------------
# The kickstart's %post is a multi-line bash script with `set -euxo pipefail`.
# A preseed value is a single line (continuations are joined with spaces), so a
# multi-line script cannot be written inline. Instead late_command writes the
# script to /root/vdi-post.sh in the installed system, line by line, and then
# runs it with bash. That keeps it a real script - which is what makes
# `set -euo pipefail` possible at all, since preseed_command itself uses
# /bin/sh (dash, no pipefail) - and it stays readable here.
#
# The script is reproduced verbatim below as a comment so it can be reviewed
# against ks.cfg without decoding anything. The printf arguments that follow it
# are exactly these lines, in this order.
#
# ---8<--- /root/vdi-post.sh ---8<---
# #!/bin/bash
# set -euo pipefail
# INV="${1:-00000}"
# LOG=/root/post-install.log
# exec >>"$LOG" 2>&1
# echo "=== VDI post-install, inventory ${INV} ==="
# HOSTNAME="EXTVDIL${INV}"
# USERNAME="vdi${INV}"
# FULLNAME="VDI-${INV}"
# PASSWORD="pwVDI#${INV}"
# ROOT_HASH='$6$3EpVOhxlL/EVU/8f$Z.M5x/x5OdzBFW2C0IoNo5KCsLURBJZnp1BgcMWFz8gsjEPSgAlBKEs7CgZnRAGjbrEzgvUCEydmjtZYvUraJ/'
# printf "%s\n" "$HOSTNAME" > /etc/hostname
# printf "127.0.1.1\t%s\n" "$HOSTNAME" >> /etc/hosts
# hostnamectl set-hostname "$HOSTNAME" 2>/dev/null || true
# getent group sudo >/dev/null || groupadd sudo
# if ! id VDI-ADMIN >/dev/null 2>&1; then
# useradd -m -s /bin/bash -G sudo -c "VDI Admin" -p "$ROOT_HASH" VDI-ADMIN
# fi
# if ! id "$USERNAME" >/dev/null 2>&1; then
# useradd -m -s /bin/bash -c "$FULLNAME" "$USERNAME"
# fi
# printf "%s:%s\n" "$USERNAME" "$PASSWORD" | chpasswd
# if ! wget -q -O /usr/share/keyrings/teamviewer.asc https://linux.teamviewer.com/pubkey/currentkey.asc; then
# echo "teamviewer key download failed"
# fi
# apt-get update || echo "apt-get update failed"
# if [ -d /root/VDI-Linux/.git ]; then
# ( cd /root/VDI-Linux && git pull ) || echo "git pull failed - continuing"
# else
# git clone https://nachos386.lcube-server.de/REYHER-Systemtechnik-Public/VDI-Linux /root/VDI-Linux || echo "git clone failed - continuing"
# fi
# if [ -f /root/VDI-Linux/update_local_repo.py ]; then
# ( cd /root/VDI-Linux && python3 ./update_local_repo.py ) || echo "update_local_repo.py failed"
# fi
# apt-get update || echo "apt-get update failed"
# apt-get install -y icaclient ctxusb || echo "citrix install failed"
# apt-get install -f -y || true
# apt-get install -y teamviewer || echo "teamviewer install failed"
# cat > /root/auto_update.sh <<EOF
# #!/bin/bash
# # Delegates to the single offline-update implementation, which
# # update_local_repo.py installs and vdi-offline-update.timer also runs every 6h.
# if [ -x /usr/local/sbin/vdi-offline-update ]; then
# exec /usr/local/sbin/vdi-offline-update
# fi
# echo "auto_update.sh: vdi-offline-update not installed yet"
# EOF
# chmod +x /root/auto_update.sh
# cat > /etc/systemd/system/disable-sleep.service <<EOF
# [Unit]
# Description=Disable sleep and idle actions permanently
# After=multi-user.target
#
# [Service]
# Type=simple
# ExecStart=/usr/bin/systemd-inhibit --what=sleep:idle --who="Permanent Inhibit" --why="Keep system always awake" --mode=block /bin/sleep infinity
# Restart=always
#
# [Install]
# WantedBy=multi-user.target
# EOF
# printf "%s\n" "*/10 * * * * root cd /root/VDI-Linux && python3 update_local_repo.py >> /var/log/update_local_repo.log 2>&1" >> /etc/crontab
# printf "%s\n" "@reboot root bash -c \"until ping google.com -c1 >/dev/null 2>&1; do sleep 1; done;\" && cd /root/ && ./auto_update.sh >> /var/log/update_local_repo.log 2>&1" >> /etc/crontab
# systemctl enable disable-sleep.service || echo "enable disable-sleep failed"
# systemctl enable cron || echo "enable cron failed"
# # The offline-update timer is normally enabled by update_local_repo.py, but that
# # only runs on the 10-minute cron. Enabling it here too means a fresh install
# # gets offline updates from the first boot, not ten minutes in.
# systemctl enable vdi-offline-update.timer 2>/dev/null || true
# echo "VDI post-install complete"
# ---8<--- end /root/vdi-post.sh ---8<---
#
# Differences from the kickstart's %post, all forced by Debian:
#
# * Firefox policies path (ks.cfg:113-136) is UNCHANGED: on trixie
# /etc/firefox/policies/policies.json is the path firefox-esr actually reads,
# with MOZ_SYSTEM_POLICIES compiled in. It is written from late_command
# straight into /target (mode 644, root:root) rather than from the script,
# because no chroot is needed to create a file.
# * pip install tqdm (ks.cfg:143) -> python3-tqdm from the package list; see
# GAP 5.
# * dnf install ICAClient / ctxusb (ks.cfg:147-149) -> apt-get install icaclient
# ctxusb, after update_local_repo.py has built the local flat repo at
# /var/local/citrix-repo. The Fedora RPM names differ in case from the Debian
# package names.
# * dnf install teamviewer from the yum repo (ks.cfg:151-167) -> apt-get from
# TeamViewer's apt repo. The repo file is written by late_command; the suite
# is "stable" (TeamViewer publishes stable, not trixie) and the key is
# fetched over https and pinned with signed-by.
# * /root/auto_update.sh no longer contains the pkcon sequence inline. It
# delegates to /usr/local/sbin/vdi-offline-update, which update_local_repo.py
# installs and which vdi-offline-update.timer also runs every 6 hours. One
# implementation instead of two, and the timer means the offline update is
# prepared on a schedule rather than only at boot.
#
# UPDATE BEHAVIOUR - parity with the Fedora clients:
# * No password for updates. Debian's own polkit rules only let a sudo-group
# user trigger "upgrade-system" and "trigger-offline-update" without a
# prompt; "system-sources-refresh" and "system-update" (what pkcon refresh
# and pkcon update use) are auth_admin, so a desktop user IS asked. The rule
# update_local_repo.py installs fills that gap. Measured with pkcheck: with
# the rule rc=0 (authorised), without it rc=2 (authentication required).
# * Offline update works. Debian 13 PackageKit 1.3.1 supports
# offline-get-prepared and offline-trigger, and
# packagekit-offline-update.service is wired into system-update.target.
# Verified end to end: offline-trigger creates
# /system-update -> /var/lib/PackageKit/prepared-update holding the
# downloaded package list, which systemd applies on the next boot.
# * The Fedora `if pkcon offline-get-prepared; then pkcon offline-trigger` guard
# is load-bearing and kept: offline-get-prepared exits 4 when nothing is
# prepared, and triggering anyway leaves a dangling /system-update symlink
# that fails the next boot.
# * `git clone` is FAIL-SOFT here. The kickstart runs with set -e and aborts the
# whole %post if the internal Gitea server is unreachable, which leaves a
# half-provisioned machine. The 10-minute cron job picks the clone up on its
# next run, so the Debian path logs the failure and continues. This is a
# deliberate behavioural difference, not an oversight.
# * `openssl passwd -6` in %pre (ks.cfg:83) produced a SHA-512 crypt hash for
# the vdi<NNNNN> password. d-i has no openssl, so that password is set in
# the installed system with chpasswd, which uses whatever crypt scheme the
# target's PAM default is - yescrypt on trixie, not SHA-512. The password
# VALUE is identical; only the stored hash format differs. The root and
# VDI-ADMIN hashes are still the kickstart's exact SHA-512 strings, passed
# through unchanged, so those two accounts match the Fedora machines exactly.
# * `systemctl start disable-sleep.service` (ks.cfg:217) is dropped and only
# `systemctl enable` is kept: late_command runs inside a chroot where systemd
# is not the init process, so `start` cannot work. The unit is enabled and is
# WantedBy=multi-user.target, so it starts on first boot - same end state.
# For the same reason `systemctl daemon-reload` is not called; nothing needs
# it before boot.
# * `systemctl restart crond` (ks.cfg:190) -> `systemctl enable cron`. The
# service is called cron on Debian, and it is not running in the chroot.
# * The commented-out hourly auto_update cron line (ks.cfg:186) is not carried
# over - it is dead in the kickstart too.
#
# late_command:
# 1. writes /etc/firefox/policies/policies.json (ks.cfg:113-135)
# 2. writes /etc/apt/sources.list.d/teamviewer.list (ks.cfg:152-162)
# 3. writes /root/vdi-post.sh from the lines above and runs it under bash
d-i preseed/late_command string \
inv=$(cat /tmp/vdi.inventory 2>/dev/null || echo 00000); \
echo "VDI: late_command, inventory=${inv}" >> /var/log/vdi-preseed.log; \
mkdir -p /target/etc/firefox/policies; \
printf "%s\n" "{" " \"policies\": {" " \"ManagedBookmarks\":" " [" " {" " \"toplevel_name\": \"Reyher\"" " }," " {" " \"name\": \"Arbeit\"," " \"url\": \"https://workspace.reyher.de/\"" " }" " ]" " }" "}" > /target/etc/firefox/policies/policies.json; \
chmod 644 /target/etc/firefox/policies/policies.json; \
chown 0:0 /target/etc/firefox/policies/policies.json; \
mkdir -p /target/etc/apt/sources.list.d /target/usr/share/keyrings; \
printf "%s\n" "deb [signed-by=/usr/share/keyrings/teamviewer.asc] https://linux.teamviewer.com/deb stable main" > /target/etc/apt/sources.list.d/teamviewer.list; \
printf "%s\n" '#!/bin/bash' 'set -euo pipefail' 'INV="${1:-00000}"' 'LOG=/root/post-install.log' 'exec >>"$LOG" 2>&1' 'echo "=== VDI post-install, inventory ${INV} ==="' 'HOSTNAME="EXTVDIL${INV}"' 'USERNAME="vdi${INV}"' 'FULLNAME="VDI-${INV}"' 'PASSWORD="pwVDI#${INV}"' "ROOT_HASH='\$6\$3EpVOhxlL/EVU/8f\$Z.M5x/x5OdzBFW2C0IoNo5KCsLURBJZnp1BgcMWFz8gsjEPSgAlBKEs7CgZnRAGjbrEzgvUCEydmjtZYvUraJ/'" 'printf "%s\n" "$HOSTNAME" > /etc/hostname' 'printf "127.0.1.1\t%s\n" "$HOSTNAME" >> /etc/hosts' 'hostnamectl set-hostname "$HOSTNAME" 2>/dev/null || true' 'getent group sudo >/dev/null || groupadd sudo' 'if ! id VDI-ADMIN >/dev/null 2>&1; then' ' useradd -m -s /bin/bash -G sudo -c "VDI Admin" -p "$ROOT_HASH" VDI-ADMIN' 'fi' 'if ! id "$USERNAME" >/dev/null 2>&1; then' ' useradd -m -s /bin/bash -c "$FULLNAME" "$USERNAME"' 'fi' 'printf "%s:%s\n" "$USERNAME" "$PASSWORD" | chpasswd' 'if ! wget -q -O /usr/share/keyrings/teamviewer.asc https://linux.teamviewer.com/pubkey/currentkey.asc; then' ' echo "teamviewer key download failed"' 'fi' 'apt-get update || echo "apt-get update failed"' 'if [ -d /root/VDI-Linux/.git ]; then' ' ( cd /root/VDI-Linux && git pull ) || echo "git pull failed - continuing"' 'else' ' git clone https://nachos386.lcube-server.de/REYHER-Systemtechnik-Public/VDI-Linux /root/VDI-Linux || echo "git clone failed - continuing"' 'fi' 'if [ -f /root/VDI-Linux/update_local_repo.py ]; then' ' ( cd /root/VDI-Linux && python3 ./update_local_repo.py ) || echo "update_local_repo.py failed"' 'fi' 'apt-get update || echo "apt-get update failed"' 'apt-get install -y icaclient ctxusb || echo "citrix install failed"' 'apt-get install -f -y || true' 'apt-get install -y teamviewer || echo "teamviewer install failed"' 'cat > /root/auto_update.sh <<EOF' '#!/bin/bash' '# Delegates to the single offline-update implementation, which' '# update_local_repo.py installs and vdi-offline-update.timer also runs every 6h.' 'if [ -x /usr/local/sbin/vdi-offline-update ]; then' ' exec /usr/local/sbin/vdi-offline-update' 'fi' 'echo "auto_update.sh: vdi-offline-update not installed yet"' 'EOF' 'chmod +x /root/auto_update.sh' 'cat > /etc/systemd/system/disable-sleep.service <<EOF' '[Unit]' 'Description=Disable sleep and idle actions permanently' 'After=multi-user.target' '' '[Service]' 'Type=simple' 'ExecStart=/usr/bin/systemd-inhibit --what=sleep:idle --who="Permanent Inhibit" --why="Keep system always awake" --mode=block /bin/sleep infinity' 'Restart=always' '' '[Install]' 'WantedBy=multi-user.target' 'EOF' 'printf "%s\n" "*/10 * * * * root cd /root/VDI-Linux && python3 update_local_repo.py >> /var/log/update_local_repo.log 2>&1" >> /etc/crontab' 'printf "%s\n" "@reboot root bash -c \"until ping google.com -c1 >/dev/null 2>&1; do sleep 1; done;\" && cd /root/ && ./auto_update.sh >> /var/log/update_local_repo.log 2>&1" >> /etc/crontab' 'systemctl enable disable-sleep.service || echo "enable disable-sleep failed"' 'systemctl enable cron || echo "enable cron failed"' '# The offline-update timer is normally enabled by update_local_repo.py, but that' '# only runs on the 10-minute cron. Enabling it here too means a fresh install' '# gets offline updates from the first boot, not ten minutes in.' 'systemctl enable vdi-offline-update.timer 2>/dev/null || true' 'echo "VDI post-install complete"' > /target/root/vdi-post.sh; \
chmod 700 /target/root/vdi-post.sh; \
in-target bash /root/vdi-post.sh "$inv"
# ===========================================================================
# GAPS - what the preseed mechanism cannot reproduce, consolidated
# ===========================================================================
# 1. `user --name=VDI-ADMIN` - impossible. user-setup rejects uppercase names
# and re-prompts (hangs an unattended install). Done in late_command with
# useradd instead. wheel -> sudo.
# 2. Disk detection cannot run in preseed/early_command - disks are not visible
# yet. Done in partman/early_command, the hook Debian documents for exactly
# this.
# 3. `lsblk` and `openssl` do not exist in d-i. Detection uses
# /sys/block/*/removable + udevadm; hashing is done in the installed system
# by chpasswd.
# 4. `chvt 3` / /dev/tty3 prompt - no chvt or openvt in d-i, and preseed_command
# redirects stdout to the log. Prompt goes to /dev/console, with a kernel
# cmdline override and a timeout so it cannot hang forever.
# 5. `pip install tqdm` - PEP 668 on Debian 13. Uses python3-tqdm.
# 6. `createrepo_c` - no Debian equivalent; apt-utils (apt-ftparchive) is
# installed instead for the local Citrix repo.
# 7. `systemctl start` inside %post - no systemd in the chroot. The unit is
# enabled instead and starts on first boot.
# 8. `printf "%05d"` on the inventory number - the kickstart's own line breaks
# on a number containing 8 or 9 (octal). Replaced with a padding loop.
# 9. Password hash format for vdi<NNNNN> - the kickstart's `openssl passwd -6`
# made SHA-512; chpasswd on trixie makes yescrypt. Same password, different
# stored hash. Root and VDI-ADMIN keep the kickstart's exact SHA-512 hashes.
# 10. The kickstart's own `printf "%05d"` bug (see 8) is fixed here, so an
# inventory number such as 00019 installs correctly on Debian and would
# not have on Fedora. Flagged rather than silently matched.
# 11. `git clone` of the internal repo is FAIL-SOFT here, where the kickstart
# (which runs under `set -euxo pipefail`) would abort the whole %post. The
# reason: on Fedora the repo host was reachable during install; on a Debian
# VDI the install may legitimately finish before the corporate network is up,
# and aborting would leave a half-configured machine. The clone is logged and
# the 10-minute cron job retries it. THIS IS A DELIBERATE BEHAVIOURAL
# DIFFERENCE, not an oversight - if the repo must be present before first
# boot, this line needs to fail hard instead and the installer needs to wait
# for network.
+499
View File
@@ -0,0 +1,499 @@
# Debian port test harness
`run-tests.sh` proves that the Debian side of the VDI-Linux port actually works,
and that the Fedora side has not regressed. It is a real harness: it builds a
real apt repository from the real Citrix `.deb` packages, adds a real apt
source, and asks real apt whether it can install the result. Nothing is
simulated except the parts that would change the machine.
```sh
sudo bash debian/test/run-tests.sh
```
Run as root. It needs the two Citrix `.deb` files (see [Fixtures](#fixtures)).
Exit status is 0 when no test FAILED, 1 otherwise. A SKIP does not fail the run,
but every skip prints why it skipped and what it would have checked. **A skip is
not a pass**, and the summary says so.
## What it tests
| Test | What it proves |
|------|----------------|
| T00 | Environment: root, required tools, trixie, fixtures present |
| T01 | The `.deb` fixtures really are version `26.08.0.225` |
| T02 | `python3 -m py_compile` passes for `update_local_repo.py` and `configure_kde.py` |
| T03 | Both modules **import** cleanly on Debian (no `tqdm`, no `pip`) |
| T04 | The `tqdm` fallback is usable, not merely importable |
| T05 | The flat repo builds; `Packages` has exactly 2 stanzas at the right version |
| T06 | `apt-get update` exits 0 with no `E:`, no `Err:` and no warnings for the source |
| T07 | apt can *see* the package: correct candidate, correct origin, install resolves |
| T08 | Rebuilding twice is byte-identical and produces no duplicate stanzas |
| T09 | `sync_debian` prunes stale `.deb` files (version bump cannot leave two versions) |
| T10 | A corrupted index is rejected even with `trusted=yes` (control for T06/T07) |
| T11 | The production `local-citrix-repo.list` has the shape the harness verified |
| T12 | GPG `signed-by` path (design check; skips without a signing tool) |
| T13 | Fedora path unregressed: tracked files identical, `sync_fedora` command sequence identical |
| T14 | `bash -n` on every shell script the port adds |
| T16 | polkit rule installed, mode 644, correct actions, no over-grant, balanced, idempotent |
| T17 | A real sudo-group user is authorised **without a password** (pkcheck), with a control |
| T18 | Offline-update script/units: bash -n, `systemd-analyze verify`, timer enabled, throttle, no dangling `/system-update` |
| T19 | The preseed still generates a working `/root/vdi-post.sh` that delegates updates |
| T20 | `make-iso.sh` builds a bootable ISO with the preseed baked in (skips without a netinst ISO) |
| T21 | The executable bit is recorded as `100755` **in git**, not just on disk |
| T15 | Nothing was left behind: no source file, no cached indexes, no installs, no `__pycache__`, no polkit rule or unit residue |
### The repo build it tests
The exact production sequence, on a copy of the real `.deb` files in a temp
directory:
```sh
cd "$repo"
apt-ftparchive packages . > Packages
gzip -c Packages > Packages.gz
apt-ftparchive release . > Release
```
and the exact production source line:
```
deb [trusted=yes] file:/var/local/citrix-repo ./
```
with the path substituted for the temp directory. A flat ("trivial") archive:
no `dists/` tree, suite `./`.
## What it does NOT test, and cannot
Being explicit matters more than the green summary.
1. **A real d-i install.** The harness never boots an installer. `debian/preseed.cfg`
is owned and validated by another change; this harness does not test it at all.
Note that `debconf-set-selections` validates line shape only - it silently accepts
an invented question name - so it is not evidence that directives exist.
2. **An actual GUI session.** Nothing here starts Plasma, and no test asserts that
`configure_kde.py` produces a working desktop. T03 proves it *imports*; whether
the touchpad and power settings take effect on a real session is untested.
`kwriteconfig6` is not installed here, so `configure_kde.KWRITE` is `None` and
every write would no-op. That path needs a real Plasma machine.
3. **The Citrix preinst/postinst maintainer scripts.** `apt-get install --simulate`
resolves dependencies; it does not run the package's scripts. Whether
`icaclient`'s postinst succeeds on a real machine is untested. This is the
single biggest gap: a dependency-resolvable package can still fail to configure.
4. **A real d-i/target filesystem for the repo path.** The harness builds the repo
in a temp directory, never at `/var/local/citrix-repo`. It asserts the
*shape* is identical (T11), not that the production path is writable in a
target environment.
5. **The network path.** The Gitea release API and the download code are not
exercised. T09 redirects the source files to a local directory, so
`download_file` is only exercised indirectly. A changed release asset name
would not be caught here.
6. **`apt-get update` inside a d-i chroot.** The preseed's `late_command` runs in
an `in-target` context where apt behaves differently (no `_apt` user, different
permissions). Untested.
7. **Fedora at runtime.** T13 compares source and command sequences; it does not
run `createrepo_c`/`dnf`/`rpm` on Fedora. The command sequence matching is
strong evidence but it is not an execution test. A Fedora 44 WSL distro exists
on the development machine and was not used.
8. **A real desktop session.** T17 proves polkit authorises a sudo-group user
without a password, which is the actual requirement, but it does not open a
GUI and click an update. `pkcon refresh` from a live Plasma session, with an
authentication agent running, is not exercised.
9. **An actual offline update reboot.** T18 checks that `/system-update` is armed
with an existing target and that `systemd-analyze verify` is clean. It does not
reboot and let `packagekit-offline-update.service` apply anything. Whether the
update actually installs at the next boot is untested - only that it was
correctly prepared.
10. **`package-install` end to end.** The polkit rule also grants
`package-install`, but T17 only checks `system-sources-refresh` (the action
`pkcon refresh` uses) and that `package-remove` is *not* granted. Installing a
package from a desktop session without a password is not exercised.
11. **Actually booting the built ISO.** T20 proves the image is structurally
correct and the preseed is on it, but it never boots it in a VM. Whether the
installer runs unattended end to end, and whether the inventory prompt behaves,
is untested. `xorriso` says the boot record is intact; only a real (virtual)
machine says the firmware agrees.
## Two spec'd checks that cannot fail, and what replaced them
This is the most important thing in this file. Two checks that look like tests
are not tests.
### `apt-get update` exiting 0 with no `E:` lines
Measured on Debian 13: a repo whose `Packages` is **unreadable** produces
```
Err:4 file:/tmp/.../repo ./ Packages
Could not open file .../Packages - open (13: Permission denied)
```
and `apt-get update` still **exits 0 with no `E:` lines**. The same is true of a
repo with **no `Release` file at all**, and of a repo with **duplicate stanzas**.
So "exit 0 and no `E:`" passes on a broken repo.
The harness runs the spec'd check as T06 *and* the stronger check separately: no
`Err:` lines, no `W:` lines for that source, and then T07 requires apt to name the
exact version from that exact directory. T10 is the control that proves the
strong checks can fail: it corrupts `Packages` after `Release` was built and
asserts apt **rejects** it with a hash mismatch. Without T10, T06/T07 could be
passing vacuously.
### `git diff main -- ks.cfg`
`ks.cfg` is **not in the repository**. It is not in `main`, not in `debian-port`,
and `git log --all -- ks.cfg` is empty. It lives one level above the repo, in the
parent directory, untracked.
So `git diff main -- ks.cfg` exits 0 and prints nothing - because the path does
not exist on either side, not because the file is unchanged. The harness detects
this with `git cat-file -e main:ks.cfg` and reports it as **SKIP, explicitly
labelled VACUOUS**, rather than as a pass. It then prints the sha256 of the real
out-of-tree file so a change to it is at least visible.
## Line endings will fool you
This repo is checked out on Windows. Every tracked file in the working tree has
CRLF line endings; every blob in git has LF. A plain `git diff main` therefore
reports **all five files as completely rewritten**, including
`RPM-GPG-KEY-citrix-local` with 104 changed lines - the key itself is byte-identical.
The harness compares modulo CRLF (`tr -d '\r' | cmp`). If you see a huge diff,
check line endings before believing it.
## The apt index cache will fool you
`apt-cache policy` and `apt-get update` read cached indexes in
`/var/lib/apt/lists`. During development, a **wrong GPG key** appeared to be
accepted - `exit 0`, no `E:`, package still visible - purely because a good index
was cached from an earlier run.
Every case that must fail purges that repo's cached index files first
(`purge_apt_lists_for`). Any test that checks "can apt see the package" without
purging is testing the cache, not apt.
Related: `/tmp` is wiped between separate `wsl` invocations on this machine
(`systemd-tmpfiles`). Anything expected to survive across invocations must live
in `/root`.
## GPG signing: why `trusted=yes` is the right call
Production does not sign the Debian repo, and T12 exists to check that decision
rather than assume it. A stock trixie ships **no `gpg`** - only `/usr/bin/sqv`,
the Sequoia verifier that apt calls internally. So signing would add a `gpg`
dependency that Debian 13 does not have by default, in an installer environment
where new dependencies are the fragile thing.
The signing path was measured out of band (a throwaway key generated with Fedora
WSL's `gpg`, because Debian has none), with the apt cache purged between cases:
| Keyring | Result |
|---------|--------|
| armored `.asc`, correct key | exit 0, no `E:`, package visible |
| armored `.asc`, **wrong** key | exit 100, `E:`, `Missing key`, not visible |
| binary `.gpg`, correct key | exit 0, no `E:`, package visible |
| binary `.gpg`, **wrong** key | exit 100, `E:`, `Missing key`, not visible |
| `trusted=yes`, no signature | exit 0, no `E:`, package visible |
Two conclusions:
- `signed-by` **works correctly** on a flat `file:` repo on trixie, for both
keyring formats. It is not broken; it is simply not worth it here.
- `trusted=yes` does **not** mean "no integrity checking". T10 shows a tampered
`Packages` is rejected with `E: ... Hash Sum mismatch` regardless. Signing
would only add proof of *authorship*, which is meaningless for a repository the
machine builds from packages it just downloaded and verified itself.
T12 skips loudly when no signing tool is present, which is the normal case on a
stock trixie. Install `gpg` to make it run.
## Fixtures
The two real packages are expected next to the repo, not inside it:
```
LinuxISO/
icaclient_26.08.0.225_amd64.deb (256 MB)
ctxusb_26.08.0.225_amd64.deb (178 KB)
VDI-Linux/ <- the repo
debian/test/run-tests.sh <- this harness
```
Override with `DEB_DIR=/path/to/debs sudo -E bash debian/test/run-tests.sh`.
The 256 MB file is copied into a temp directory, which is fast on native
filesystem and slow off `/mnt/c`. If `/tmp` is small, set `TMPDIR` to somewhere
with ~600 MB free.
## T17 is the test that matters, and why it needs a control
The user's requirement is that a desktop user can update **without an admin
password**. Asserting that the rule file contains the right action names proves
nothing about whether polkit acts on it - a rule can be syntactically perfect,
in the right directory, and still never match (which is exactly what happened
during development with a `subject.local == true` clause).
So T17 asks polkit itself:
1. Start a process owned by a real member of group `sudo` (`setsid`, so nothing
blocks), then `pkcheck --action-id ...system-sources-refresh --process <pid>`
as root. Assert **rc=0**.
2. **The control:** move the rule away, restart polkit, repeat. Assert **rc=2**
(authentication required). Then restore.
Without step 2 the test cannot fail: a polkit configured to answer YES to
everything would also give rc=0. The control is what makes step 1 evidence.
It also asserts the rule does **not** grant `package-remove`, `package-reinstall`
or `package-install-untrusted` - a user who can remove packages without a
password can break the machine.
That refusal is checked three ways, because a negative assertion is easy to
write in a way that cannot fail:
1. The rule **text** must not mention the action (T16).
2. polkit itself must refuse it: T17 starts its **own** detached sleeper owned by
the sudo-group user, proves `/proc/<pid>` is owned by that user, then asks
`pkcheck --action-id ...package-remove --process <pid>` and requires rc=2.
A missing process or any unexpected rc is a **FAIL**, never a pass - a 127
must not be able to masquerade as "denied".
3. **The check was proven able to fail.** With `package-remove` added to the
rule by hand and polkit restarted, `pkcheck` returned **rc=0** (granted), so
assertion 2 goes red. Restored afterwards and verified by sha256. Without
this step the assertion would only be known to pass, not known to be capable
of failing.
`pkcheck` is only conclusive because it consults the live polkitd. If polkit is
not installed, T16 and T17 **skip** with a reason rather than passing quietly.
## T18: the dangerous failure mode
A dangling `/system-update` symlink **fails the next boot**. The offline-update
script arms that symlink, so the harness asserts, after every run, that if
`/system-update` exists then its `readlink -f` target exists too. It is checked
both immediately after the run and again after the forced (stamp=0) run, which
is the one most likely to arm it.
Also asserted, because it is a real behaviour and not a detail:
- Running the script twice in a row is **throttled** (prints "skipping").
- Setting the stamp to `0` defeats the throttle - so it is time-based, not a
permanent latch.
- `pkcon` exit 5 means "no packages to update" and must not be reported as
`download failed`. On an up-to-date box the output must not contain
"download failed".
## T19: why it never executes the generated script
The preseed's `late_command` writes `/root/vdi-post.sh` and then runs it with
`in-target`. That script writes `/etc/hostname`, `/etc/hosts`, `/etc/crontab`
and systemd units **by absolute path** - running it here would reconfigure the
machine the tests are running on.
T19 therefore only *regenerates* the script by running the preseed's own
`printf` into a temp file, then checks it: `bash -n`, that it delegates to
`/usr/local/sbin/vdi-offline-update` instead of duplicating the `pkcon`
sequence (comments stripped first, so the explanatory comment does not produce
a false positive), and that it still enables `cron` and
`vdi-offline-update.timer`.
Extracting it is fiddly, and the naive approaches are all wrong in ways that
look like preseed bugs:
- A regex that crosses `;` captures the **firefox** `printf` too, which then
tries to write `/target/etc/firefox` and fails.
- Splitting on `;` breaks, because the payload contains `;` and `>` inside
quoted arguments.
- Leaving the leading `\` of the first continuation line makes `sh -c` skip the
`printf` entirely, producing a "No such file" that looks exactly like a
preseed defect.
The harness anchors on two unambiguous markers instead: the payload's own first
argument `'#!/bin/bash'` and the `> /target/root/vdi-post.sh` redirect. It also
asserts the captured text does **not** contain `ManagedBookmarks`, so a future
change to the preseed fails loudly rather than silently testing the wrong
block.
## Tests that mutate the machine, and how that is undone
T16-T19 install a polkit rule and systemd units and can arm `/system-update`.
T15 asserts no collateral damage, so every mutated path is **backed up before
the test and restored at teardown**:
| Path | How it is handled |
|------|-------------------|
| `/etc/polkit-1/rules.d/60-vdi-no-password-updates.rules` | backed up, restored |
| `/usr/local/sbin/vdi-offline-update` | backed up, restored |
| `/etc/systemd/system/vdi-offline-update.{service,timer}` | backed up, restored |
| `/var/lib/vdi-offline-update.last` | backed up, restored |
| `/system-update` | backed up as a symlink target, restored; **never `rm -rf`** |
`restore_path` records whether a path was `present`, `absent` or a `symlink`
before the run, so "it did not exist and must be gone" is distinguishable from
"the backup failed". For an absent path it removes only a regular file or
symlink - it never recurses into a directory. The same restores run in the
`EXIT` trap, so an aborted run still cleans up.
## T20: the ISO builder
T20 needs a real Debian netinst ISO and **does not download one** - a test that
fetches 792 MB before it can start is a test nobody runs. It looks for
`/root/trixie-netinst.iso` (or `NETINST_ISO=/path`), and without one it skips
and lists what it would have checked.
With an ISO present it runs `make-iso.sh` into a temp directory (about 3 seconds)
and asserts:
- It **refuses** to overwrite an existing output, and refuses to write over its
own input. Both are tested by expecting a non-zero exit, not by reading the code.
- `/preseed.cfg` on the output is byte-identical to `debian/preseed.cfg`.
Extracted to a real file first - `-extract ... /dev/stdout` does not work.
- **Every** kernel line under `/isolinux` and `/boot/grub` carries
`preseed/file=/cdrom/preseed.cfg`. Counted, not sampled: on 13.7.0 it is 40
lines (20 BIOS + 20 UEFI), and the assertion is `patched == total`. A
`> 0` check would pass while half the entries still prompt.
- `isolinux/gtk.cfg` specifically is patched. That file holds the BIOS *default*
entry; `isolinux.cfg` is only `include` and `default vesamenu.c32`, so patching
the obvious files leaves the default boot prompting. That is the bug this test
exists to catch, and it is asserted by name rather than left implicit.
- No kernel line carries the parameter **twice** (a re-run of the patch, or a
`-map` applied on top of an already-patched file).
- Both a BIOS and a UEFI El Torito image are present.
- No file from the source ISO is missing from the output (1010 files on 13.7.0).
- Output size is within 16 MB of the source. The measured delta is -704 KB. The
naive extract-and-rebuild implementation bloats 792 MB -> 988 MB because
Debian's ISO shares identical file extents between paths; this guards that
regression.
### `grep -c` exits 1 on zero, and that will corrupt your count
While writing T20 this produced a wrong total: `grep -c ... || echo 0` prints
`0` **and then** appends another `0` when there are no matches, because `grep -c`
prints the count and *also* exits 1. The result is `0\n0`, and `$((total + 0\n0))`
is a syntax error. The harness swallows the exit status only (`|| true`) and
validates the value with a `case` before doing arithmetic.
## Two corrections that are now asserted
**`subject.local` must not come back into the polkit rule.** An earlier version
of the rule included `subject.local == true` to restrict it to a seat physically
in front of the machine. It never matches: `pkcheck` returns 2 with the clause
and 0 without it, for the same user. If it returns, passwordless updates stop
working while every other T16 assertion still passes - so T16 now asserts the
clause is **absent**, with the reason in a comment.
**"the timer is enabled" is not a stable assertion on its own.** Enabling is done
by `systemctl enable vdi-offline-update.timer` inside
`install_debian_update_policy()`, and that only persists when systemd is the
running init. T18 therefore drives the installer function first, then asserts,
and **skips** the assertion with a reason when systemd is not PID 1.
## A killed run leaves apt permanently broken, and the lock cannot help
The harness removes its own apt source in an `EXIT` trap. A run that is killed
(the turn is cancelled, the terminal is closed, `SIGKILL`) never reaches that
trap, so `/etc/apt/sources.list.d/zz-vdi-test-<pid>.list` survives pointing at a
temp directory that no longer exists. Every subsequent `apt-get update` then
fails with `Failed to fetch ... File not found`, and T06/T07 report that as a
port defect. This was observed: a leftover `zz-vdi-test-250.list` from another
run broke three T06 assertions while the port was fine.
The `flock` does not prevent it, because there is no concurrent process - just
residue. So at startup, under the lock, the harness sweeps any
`zz-vdi-test-*.list` whose target directory is gone, and says so. That is safe
precisely because the lock guarantees no peer run is alive at that moment.
## T21: executable on disk is not executable in a clone
This repo is developed on a Windows checkout with `core.fileMode=false`, so git
records mode `100644` regardless of the mode on disk. Both scripts were
executable locally and non-executable in the index - a fresh Linux clone gets
`Permission denied` running `./debian/test/run-tests.sh`.
T21 asserts `git ls-files -s` reports `100755` for `debian/test/run-tests.sh`
and `debian/make-iso.sh`. It skips honestly when git is unavailable or the
directory is not a checkout. Fix a failure with:
```sh
git update-index --chmod=+x <path>
```
## T19 cross-checks the preseed against the installer
T19 asserts the generated `auto_update.sh` delegates to
`/usr/local/sbin/vdi-offline-update`. That string is hard-coded in the preseed,
while the *installer* of that path lives in `update_local_repo.py` - two
independent files with nothing tying them together. If the installer's path ever
changed, the preseed would keep pointing at the old one and `auto_update.sh`
would degrade to printing `vdi-offline-update not installed yet`:
gracefully, silently, with every other assertion still green.
So T19 reads `update_local_repo.OFFLINE_UPDATE_SCRIPT` and asserts the generated
script names that same path. It skips if that constant does not exist.
What T19 still does **not** prove: that the helper exists and runs on a real
target. It is installed by `update_local_repo.py` at first cron run, so on a
fresh install `auto_update.sh` may legitimately find it absent. That ordering is
by design, not a defect, but it means T19 is evidence about the *contract*
between the two files, not about the end state of an installed machine.
## Requirements
- Debian 13 (trixie), root.
- `apt-ftparchive`, `apt-get`, `apt-cache`, `dpkg-deb`, `python3`, `gzip` - all
present in a stock install.
- `git` **for T13 only**. It is not part of a stock trixie image; without it T13
skips and says so. Install it if you want the Fedora regression checks to run:
`apt-get install -y --no-install-recommends git`. Note this changes the test
machine, which is why the harness treats its absence as a skip rather than
installing it itself.
- `gpg` **for T12 only**, and only if you want to re-check the signing decision.
- `xorriso` **for T20 only**. Without it T20 skips with a reason.
- A Debian netinst ISO **for T20 only**, at `/root/trixie-netinst.iso` or
`NETINST_ISO=/path/to/netinst.iso`. It is never downloaded. The build itself
takes about 3 seconds and needs ~1.6 GB free in `TMPDIR` (source plus output;
the source is not copied, only written to the output).
## Safety
The harness is designed to be safe to run on a machine you care about.
- It never writes to `/var/local/citrix-repo`. It records that directory's mtime
before the run and asserts it is unchanged in T15.
- It never installs anything. The only `apt-get install` is `--simulate`. T15
compares the installed package count before and after.
- It adds exactly one apt source file, `/etc/apt/sources.list.d/zz-vdi-test-$$.list`,
and removes it. T15 verifies the removal happened.
- It removes only the apt index files it created, matched by the encoded repo path,
never `/var/lib/apt/lists` wholesale.
- It removes any keyring it installed, matched by the `zz-vdi-test-*` prefix, and
only `rmdir`s `/etc/apt/keyrings` (which fails harmlessly if it was already there
with other keys in it).
- It never writes `__pycache__` into the repo: `PYTHONDONTWRITEBYTECODE=1` and
`PYTHONPYCACHEPREFIX` are set, and T15 asserts the repo is clean.
- All scratch work happens in one `mktemp -d` directory, removed at the end.
- A failing test does not abort the run, so you get the whole picture in one pass.
## Interpreting a failure
- **T05/T06/T07 failing together** - the repo build is broken. Look at T05 first.
- **T07 fails but T05 passes** - the repo is fine but apt cannot consume it; check
directory permissions (apt drops to `_apt`, so the repo path must be traversable).
- **T09 fails** - `sync_debian` is leaving old versions in the published
directory. On Debian, filenames carry the version, so copying without deleting
leaves every previous release indexed and makes rollback impossible.
- **T13 fails on the command sequence** - compare the printed `MAIN-CMDS` and
`FEDORA-CMDS` lists. Both sides are normalised to `<REPO>`; if they differ, the
Fedora path genuinely changed.
- **T15 fails on residue** - the teardown did not finish. Check the messages
immediately above it.
Vendored Executable
+1997
View File
File diff suppressed because it is too large. Load diff
+21
View File
@@ -0,0 +1,21 @@
# Local Citrix repository for Debian-family clients.
#
# The apt counterpart of local-citrix-repo.repo (which dnf uses on Fedora).
# update_local_repo.py copies this file to
# /etc/apt/sources.list.d/local-citrix-repo.list once the packages are published.
#
# This is a flat ("trivial") apt archive: the packages, Packages, Packages.gz and
# Release all sit directly in /var/local/citrix-repo. That is why the suite is
# "./" - a path ending in a slash with no component - rather than a codename.
#
# trusted=yes is deliberate. The repository is generated on this machine from
# packages update_local_repo.py has just downloaded and verified, so there is no
# third party to authenticate against and signing would only mean generating and
# trusting a key on every fresh install. On Fedora the equivalent file keeps
# gpgcheck=1 because that path already has an RPM signing key.
#
# Unlike dnf, apt has no per-source metadata expiry: the index is re-read only
# when `apt-get update` runs. update_local_repo.py runs it, and the 10-minute
# cron job installed by the preseed runs update_local_repo.py, so the index does
# not go stale in practice.
deb [trusted=yes] file:/var/local/citrix-repo ./
+693 -47
View File
@@ -1,37 +1,207 @@
#!/usr/bin/env python3
"""Keep the local Citrix package repository in sync with the latest Gitea release.
import urllib.request
import os
import urllib.error
import threading
from concurrent.futures import ThreadPoolExecutor
from tqdm import tqdm
import logging
import time
The script supports both package families that the VDI clients run:
* **Fedora** (the original target): downloads ``.rpm`` assets and publishes them
through a ``createrepo_c`` repository at ``/var/local/citrix-repo``, read by
dnf through ``/etc/yum.repos.d/local-citrix-repo.repo``.
* **Debian** (this branch): downloads ``.deb`` assets and publishes them through
a flat ``apt-ftparchive`` repository at the same path, read by apt through
``/etc/apt/sources.list.d/local-citrix-repo.list``.
The family is detected at runtime from ``/etc/os-release``. The Fedora code
path is unchanged from the version that has been deployed for months: same
asset filenames, same commands, same order. Adding Debian support must not
alter the behaviour of an existing Fedora client, so every Debian-specific
step is behind the family check.
Both paths share the download, hash-verification and "is there a newer
release?" logic.
"""
import datetime
import hashlib
import json
import datetime
import logging
import os
import shutil
import subprocess
import threading
import time
import urllib.error
import urllib.request
from concurrent.futures import ThreadPoolExecutor
try:
from tqdm import tqdm
except ImportError: # pragma: no cover - exercised on a bare Debian install
# tqdm is cosmetic: it only draws the download progress bar. A stock Debian
# 13 image has neither pip nor tqdm, and dying at import time here would
# take down the whole provisioning run over a progress bar. Fall back to a
# no-op so the script still works; the preseed installs python3-tqdm from
# apt so the bar is present in practice.
class tqdm: # noqa: N801 (deliberately shadows the real class)
def __init__(self, *args, **kwargs):
pass
def update(self, _n=1):
pass
def close(self):
pass
logging.basicConfig(level=logging.INFO, format='%(asctime)s - Thread %(threadName)s - %(message)s')
# Update the local repository via git pull before proceeding
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
REPO_OWNER = "REYHER-Systemtechnik-Public"
REPO_NAME = "VDI-Linux"
API_BASE = "https://nachos386.lcube-server.de/api/v1"
# Where downloaded packages are staged before being published.
STAGING_DIR = "/temp/packages"
LAST_RELEASE_FILE = os.path.join(STAGING_DIR, "last_release.json")
# The published local repository. Same path on both families.
LOCAL_REPO_DIR = "/var/local/citrix-repo"
# Fedora: local staging path -> exact asset filename in the Gitea release.
# These names are unversioned, which is why they can be matched exactly. Do not
# change this mapping; existing Fedora clients depend on it.
FEDORA_RPM_FILES = {
os.path.join(STAGING_DIR, "ctxusb.rpm"): "ctxusb.rpm",
os.path.join(STAGING_DIR, "ICAClient.rpm"): "ICAClient.rpm",
}
# Debian: the package names as apt knows them. The release assets are named
# with a version (``icaclient_26.08.0.225_amd64.deb``), so they are matched by
# prefix rather than by exact filename.
DEBIAN_PACKAGES = ("icaclient", "ctxusb")
# If the Gitea release carries no ``.deb`` assets, look here instead. This lets
# an operator drop the two Citrix .deb files onto the machine (or point
# VDI_DEB_DIR at a directory) without having to publish a release first.
DEBIAN_FALLBACK_DIR = os.environ.get("VDI_DEB_DIR", os.path.join(STAGING_DIR, "deb"))
# ---------------------------------------------------------------------------
# Distribution detection
# ---------------------------------------------------------------------------
def detect_package_family():
"""Return ``'debian'`` or ``'fedora'`` for the running machine.
``/etc/os-release`` is the authoritative source on every distribution this
script runs on. ``ID`` is checked first and ``ID_LIKE`` second, so Ubuntu,
Mint, Kali and similar are all treated as Debian family.
"""
ident = ""
like = ""
try:
subprocess.run(['git', 'pull'], check=True, capture_output=True)
logging.info("Updated repo via git pull")
except subprocess.CalledProcessError as e:
logging.warning(f"Git pull failed (non-zero exit): {e}")
except FileNotFoundError:
logging.warning("Git not found; skipping pull")
except Exception as e:
logging.warning(f"Unexpected error during git pull: {e}")
with open("/etc/os-release", encoding="utf-8") as handle:
for line in handle:
line = line.strip()
if line.startswith("ID="):
ident = line[3:].strip().strip('"').lower()
elif line.startswith("ID_LIKE="):
like = line[8:].strip().strip('"').lower()
except OSError:
logging.warning("/etc/os-release is not readable; falling back to release files")
api_base = "https://nachos386.lcube-server.de/api/v1"
tokens = set((ident + " " + like).split())
def fetch_release_info(repo_owner, repo_name):
"""Fetch latest release info including assets from Gitea API."""
api_url = f"{api_base}/repos/{repo_owner}/{repo_name}/releases/latest"
if "debian" in tokens or "ubuntu" in tokens:
return "debian"
if tokens & {"fedora", "rhel", "centos", "rocky", "almalinux"}:
return "fedora"
# Fall back to the distribution release files, then to the package manager.
if os.path.exists("/etc/debian_version"):
return "debian"
if os.path.exists("/etc/fedora-release"):
return "fedora"
if shutil.which("apt-get"):
return "debian"
if shutil.which("dnf"):
return "fedora"
logging.warning("Could not identify the distribution; assuming Fedora")
return "fedora"
PACKAGE_FAMILY = detect_package_family()
def package_extension():
"""The asset extension this family consumes."""
return ".deb" if PACKAGE_FAMILY == "debian" else ".rpm"
def apt_lists_configured():
"""True when the local apt source file is present."""
return os.path.exists("/etc/apt/sources.list.d/local-citrix-repo.list")
def local_repo_is_populated():
"""True when the published repository has an index apt/dnf can read.
Used by the Debian path to rebuild when the repository directory has been
deleted even though the release has not changed.
"""
if PACKAGE_FAMILY == "debian":
return os.path.exists(os.path.join(LOCAL_REPO_DIR, "Packages"))
return os.path.exists(os.path.join(LOCAL_REPO_DIR, "repodata"))
# ---------------------------------------------------------------------------
# Per-user desktop shortcut
# ---------------------------------------------------------------------------
def install_desktop_shortcuts():
"""Drop ``kill_citrix.sh`` on every user's desktop."""
for user in os.listdir("/home"):
home = f"/home/{user}"
if not os.path.isdir(home):
continue
try:
desktop = subprocess.check_output(
["sudo", "-u", user, "xdg-user-dir", "DESKTOP"],
text=True
).strip()
except Exception:
# Fallback if xdg-user-dir isn't available
desktop = os.path.join(home, "Desktop")
os.makedirs(desktop, exist_ok=True)
script = os.path.join(desktop, "kill_citrix.sh")
with open(script, "w") as f:
f.write("#!/bin/bash\npkill icasessionmgr\npkill wfica\n")
os.chmod(script, 0o755)
# ---------------------------------------------------------------------------
# Gitea API
# ---------------------------------------------------------------------------
def fetch_release_info(repo_owner, repo_name, extension=None):
"""Fetch latest release info including assets from Gitea API.
``extension`` limits the returned assets to one package format. It defaults
to the running machine's family so that a Fedora client never even sees the
``.deb`` assets, and vice versa.
"""
if extension is None:
extension = package_extension()
api_url = f"{API_BASE}/repos/{repo_owner}/{repo_name}/releases/latest"
try:
with urllib.request.urlopen(api_url, timeout=30) as response:
release_info = json.loads(response.read().decode())
@@ -44,7 +214,7 @@ def fetch_release_info(repo_owner, repo_name):
assets = {}
for asset in release_info.get('assets', []):
filename = asset.get('name', '')
if filename.endswith('.rpm'):
if filename.endswith(extension):
download_url = asset.get('browser_download_url', '')
if not download_url:
logging.warning(f"No download URL for {filename}")
@@ -61,7 +231,7 @@ def fetch_release_info(repo_owner, repo_name):
assets[filename] = {'url': download_url, 'hash': hash_value}
if not assets:
logging.warning("No RPM assets found in release.")
logging.warning(f"No {extension} assets found in release.")
logging.info(f"Available assets: {[a['name'] for a in release_info.get('assets', [])]}")
else:
logging.info(f"Fetched {len(assets)} assets from API.")
@@ -81,6 +251,11 @@ def fetch_release_info(repo_owner, repo_name):
logging.error(f"Unexpected error fetching release info: {e}")
raise
# ---------------------------------------------------------------------------
# Download
# ---------------------------------------------------------------------------
def compute_sha256(file_path):
"""Compute SHA256 hash of a file."""
sha256 = hashlib.sha256()
@@ -96,6 +271,7 @@ def compute_sha256(file_path):
logging.error(f"Failed to compute hash for {file_path}: {e}")
return None
def download_chunk(url, save_path, start, end, total_size, progress_bar, lock):
try:
req = urllib.request.Request(url)
@@ -123,6 +299,7 @@ def download_chunk(url, save_path, start, end, total_size, progress_bar, lock):
except Exception as e:
logging.error(f"Unexpected error in range {start}-{end}: {e}")
def download_file(url, save_path, expected_hash=None, num_threads=4):
try:
with urllib.request.urlopen(url, timeout=30) as response:
@@ -178,7 +355,8 @@ def download_file(url, save_path, expected_hash=None, num_threads=4):
logging.error(f"An unexpected error occurred: {e}")
raise
def is_newer_release(repo_owner, repo_name, last_release_file="/temp/packages/last_release.json"):
def is_newer_release(repo_owner, repo_name, last_release_file=LAST_RELEASE_FILE):
"""Check if the current release is newer than the last downloaded one."""
try:
release_data = fetch_release_info(repo_owner, repo_name)
@@ -222,22 +400,29 @@ def is_newer_release(repo_owner, repo_name, last_release_file="/temp/packages/la
logging.error(f"Unexpected error checking release: {e}")
raise
repo_owner = "REYHER-Systemtechnik-Public"
repo_name = "VDI-Linux"
last_release_file = "/temp/packages/last_release.json"
is_newer, release_data = is_newer_release(repo_owner, repo_name, last_release_file)
if is_newer:
def save_last_release(release_data):
os.makedirs(os.path.dirname(LAST_RELEASE_FILE), exist_ok=True)
with open(LAST_RELEASE_FILE, 'w') as f:
# Save only tag and published_at; assets are transient
json.dump({'tag_name': release_data['tag_name'], 'published_at': release_data['published_at']}, f)
logging.info(f"Saved last release info to {LAST_RELEASE_FILE}")
# ---------------------------------------------------------------------------
# Fedora publishing path - unchanged from the deployed version
# ---------------------------------------------------------------------------
def sync_fedora(is_newer, release_data):
if not is_newer:
logging.info("Skipping download; no new release available.")
return
assets = release_data['assets']
if not assets:
raise Exception("No RPM assets available in the latest release. Check logs for details.")
rpm_files = {
"/temp/packages/ctxusb.rpm": "ctxusb.rpm",
"/temp/packages/ICAClient.rpm": "ICAClient.rpm"
}
for local_path, filename in rpm_files.items():
for local_path, filename in FEDORA_RPM_FILES.items():
if filename not in assets:
raise Exception(f"Required asset {filename} not found in release. Available: {list(assets.keys())}")
@@ -250,37 +435,498 @@ if is_newer:
download_file(url, local_path, expected_hash)
os.makedirs("/var/local/citrix-repo", exist_ok=True)
os.makedirs(LOCAL_REPO_DIR, exist_ok=True)
logging.info("Copying ctxusb.rpm...")
shutil.copyfile("/temp/packages/ctxusb.rpm", "/var/local/citrix-repo/ctxusb.rpm")
shutil.copyfile(os.path.join(STAGING_DIR, "ctxusb.rpm"), os.path.join(LOCAL_REPO_DIR, "ctxusb.rpm"))
logging.info("Finished copying ctxusb.rpm")
logging.info("Copying ICAClient.rpm...")
shutil.copyfile("/temp/packages/ICAClient.rpm", "/var/local/citrix-repo/ICAClient.rpm")
shutil.copyfile(os.path.join(STAGING_DIR, "ICAClient.rpm"), os.path.join(LOCAL_REPO_DIR, "ICAClient.rpm"))
logging.info("Finished copying ICAClient.rpm")
os.system("createrepo_c /var/local/citrix-repo")
os.system(f"createrepo_c {LOCAL_REPO_DIR}")
logging.info("Copying local-citrix-repo.repo...")
shutil.copyfile("./local-citrix-repo.repo", "/etc/yum.repos.d/local-citrix-repo.repo")
logging.info("Finished copying local-citrix-repo.repo")
logging.info("Copying RPM-GPG-KEY-citrix-local...")
shutil.copyfile("./RPM-GPG-KEY-citrix-local", "/var/local/citrix-repo/RPM-GPG-KEY-citrix-local")
shutil.copyfile("./RPM-GPG-KEY-citrix-local", os.path.join(LOCAL_REPO_DIR, "RPM-GPG-KEY-citrix-local"))
logging.info("Finished copying RPM-GPG-KEY-citrix-local")
os.system("rpm --import /var/local/citrix-repo/RPM-GPG-KEY-citrix-local")
os.system(f"rpm --import {LOCAL_REPO_DIR}/RPM-GPG-KEY-citrix-local")
os.system("dnf makecache")
os.system("pkcon refresh force")
os.makedirs(os.path.dirname(last_release_file), exist_ok=True)
with open(last_release_file, 'w') as f:
# Save only tag and published_at; assets are transient
json.dump({'tag_name': release_data['tag_name'], 'published_at': release_data['published_at']}, f)
logging.info(f"Saved last release info to {last_release_file}")
save_last_release(release_data)
# ---------------------------------------------------------------------------
# Debian publishing path
# ---------------------------------------------------------------------------
# The canonical apt source line. local-citrix-repo.list holds the same text and
# is the file a human edits; this constant is the fallback so that a missing or
# unreadable file cannot break the 10-minute cron job.
DEBIAN_SOURCES_LINE = "deb [trusted=yes] file:/var/local/citrix-repo ./"
DEBIAN_SOURCES_PATH = "/etc/apt/sources.list.d/local-citrix-repo.list"
def _repo_file(name):
"""Locate a file that ships alongside this script.
The Fedora path uses bare relative paths (``./local-citrix-repo.repo``),
which only works when the working directory happens to be the checkout.
The cron job does ``cd /root/VDI-Linux`` first so that is fine there, but
anything that invokes this script from elsewhere - a test, a manual run,
another wrapper - would fail with a bare FileNotFoundError. Look next to
the script first and fall back to the old relative behaviour so that a
Fedora client whose cwd differs still works exactly as before.
"""
alongside = os.path.join(os.path.dirname(os.path.abspath(__file__)), name)
if os.path.exists(alongside):
return alongside
return "./" + name
# ---------------------------------------------------------------------------
# Debian: no-password updates and the offline update
# ---------------------------------------------------------------------------
# Lets members of the "sudo" group refresh and install updates from a graphical
# session without being asked for a password, which is how the Fedora clients
# behave. Debian's own /usr/share/polkit-1/rules.d/org.freedesktop.packagekit.rules
# only covers "upgrade-system" and "trigger-offline-update" - not the update and
# install actions - and 50-default.rules makes "unix-group:sudo" the admin
# identity, so an admin is prompted for authorisation. This rule supplies the
# missing cases.
#
# Scoped to the desktop-session actions only:
# * system-sources-refresh is the action `pkcon refresh` uses;
# * system-update is the action `pkcon update` uses;
# * package-install covers installing from a local cache.
# Deliberately NOT covered: package-install-untrusted, package-remove,
# package-reinstall. Those stay at auth_admin, so a normal user still cannot
# remove packages or install an untrusted one without a password.
#
# NOTE on subject.local: an earlier version of this rule also required
# `subject.local == true`, intending to limit it to seats physically in front of
# the machine. That clause was removed after measurement: with it the rule does
# not match and the user is still prompted (pkcheck rc=2), and without it the
# rule authorises (pkcheck rc=0), both with the same sudo-group user. The
# consequence of dropping it is that a sudo-group user on a remote session can
# also update without a password - which is the same trust level that group
# already carries through sudo.
POLKIT_RULE_PATH = "/etc/polkit-1/rules.d/60-vdi-no-password-updates.rules"
POLKIT_RULE = """// Installed by VDI-Linux update_local_repo.py. Do not edit; it is rewritten.
//
// Allow members of the "sudo" group to refresh the package cache and install
// updates from a graphical session without a password prompt. This matches the
// behaviour of the Fedora clients. Everything else PackageKit can do still
// requires authorisation.
polkit.addRule(function(action, subject) {
if ((action.id == "org.freedesktop.packagekit.system-sources-refresh" ||
action.id == "org.freedesktop.packagekit.system-update" ||
action.id == "org.freedesktop.packagekit.package-install") &&
subject.isInGroup("sudo")) {
return polkit.Result.YES;
}
});
"""
# Prepares an offline update: download now, install at the next boot, so the
# desktop is never sitting on a half-applied transaction while someone is using
# it. Same intent as the Fedora auto_update.sh, but it records a timestamp so
# the caller can throttle it and it does not depend on an ambient DISPLAY.
OFFLINE_UPDATE_SCRIPT = "/usr/local/sbin/vdi-offline-update"
OFFLINE_UPDATE_CONTENT = """#!/bin/bash
# Prepare a PackageKit offline update. Installed by VDI-Linux; do not edit.
#
# Runs as root from cron, so PackageKit authorises it without a password. The
# update is downloaded now and applied by packagekit-offline-update.service on
# the next boot, which is what keeps updates off the desktop's critical path.
set -u
STAMP=/var/lib/vdi-offline-update.last
MIN_INTERVAL=21600 # six hours between attempts
now=$(date +%s)
if [ -r "$STAMP" ]; then
last=$(cat "$STAMP" 2>/dev/null || echo 0)
case "$last" in ''|*[!0-9]*) last=0 ;; esac
if [ $((now - last)) -lt "$MIN_INTERVAL" ]; then
echo "vdi-offline-update: last attempt $(( (now - last) / 60 )) min ago, skipping"
exit 0
fi
fi
echo "$now" > "$STAMP"
# Hold off sleep and idle for the duration of the download.
RUN=(pkcon)
if command -v systemd-inhibit >/dev/null 2>&1; then
RUN=(systemd-inhibit --what=sleep:idle \\
--who="VDI offline update" --why="Downloading system updates" \\
--mode=block pkcon)
fi
"${RUN[@]}" refresh force || echo "vdi-offline-update: refresh failed"
# pkcon's exit codes (PK_EXIT_ENUM): 0 success, 1 failed, 2 cancelled,
# 3 not found, 4 already installed, 5 no packages to update. Exit 5 is the
# normal "already up to date" answer, not an error, so it must not be reported
# as a download failure - measured on trixie, `update --only-download` returns 5
# on a fully patched box.
"${RUN[@]}" update --only-download
rc=$?
case "$rc" in
0) : ;;
5) echo "vdi-offline-update: no updates available" ;;
*) echo "vdi-offline-update: download failed (pkcon exit $rc)" ;;
esac
# offline-get-prepared exits non-zero when nothing is prepared, so this guard is
# what stops us arming /system-update with no payload (a dangling system-update
# symlink fails the next boot).
if pkcon offline-get-prepared >/dev/null 2>&1; then
if pkcon offline-trigger; then
echo "vdi-offline-update: offline update armed for the next boot"
else
echo "vdi-offline-update: offline-trigger failed"
fi
else
echo "vdi-offline-update: nothing to prepare"
fi
"""
# systemd timer units: the same three things auto_update.sh does, on a timer.
# Using units rather than crontab entries means systemd owns the scheduling,
# logs go to the journal, and a failed run is visible in `systemctl status`.
OFFLINE_UPDATE_SERVICE = """[Unit]
Description=Prepare a PackageKit offline update
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/vdi-offline-update
Nice=10
IOSchedulingClass=idle
"""
OFFLINE_UPDATE_TIMER = """[Unit]
Description=Prepare a PackageKit offline update periodically
[Timer]
OnBootSec=15min
OnUnitActiveSec=6h
RandomizedDelaySec=15min
Persistent=true
[Install]
WantedBy=timers.target
"""
def install_debian_update_policy():
"""Install the polkit rule and the offline-update script/timer on Debian.
Both are idempotent: each file is only rewritten when its content differs,
so a 10-minute cron run does not touch the disk or restart anything.
"""
if PACKAGE_FAMILY != "debian":
return
for path, content, mode in (
(POLKIT_RULE_PATH, POLKIT_RULE, 0o644),
(OFFLINE_UPDATE_SCRIPT, OFFLINE_UPDATE_CONTENT, 0o755),
("/etc/systemd/system/vdi-offline-update.service", OFFLINE_UPDATE_SERVICE, 0o644),
("/etc/systemd/system/vdi-offline-update.timer", OFFLINE_UPDATE_TIMER, 0o644),
):
try:
os.makedirs(os.path.dirname(path), exist_ok=True)
current = None
if os.path.exists(path):
with open(path, encoding="utf-8") as handle:
current = handle.read()
if current == content:
continue
temporary = path + ".tmp"
with open(temporary, "w", encoding="utf-8") as handle:
handle.write(content)
os.chmod(temporary, mode)
os.replace(temporary, path)
logging.info("Installed %s", path)
except OSError as error:
logging.warning("Could not install %s: %s", path, error)
# Enable the timer. `enable --now` would start it, but in a chroot there is
# no running systemd, so tolerate failure and let it come up on first boot.
if shutil.which("systemctl"):
subprocess.run(["systemctl", "daemon-reload"], check=False,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
subprocess.run(["systemctl", "enable", "vdi-offline-update.timer"], check=False,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def _match_debian_asset(assets, package_name):
"""Find the release asset for ``package_name``, ignoring its version.
Citrix names the Debian packages with the version embedded
(``icaclient_26.08.0.225_amd64.deb``), so an exact filename match would
break on every new release.
"""
for filename in sorted(assets):
lowered = filename.lower()
if lowered.startswith(package_name) and lowered.endswith(".deb"):
return filename
return None
def resolve_debian_packages(release_data):
"""Return [(filename, url_or_local_path, expected_hash)] for both packages.
Prefers the Gitea release. Falls back to ``DEBIAN_FALLBACK_DIR`` when the
release carries no ``.deb`` assets, so an operator can stage the two files
locally instead of publishing a release.
"""
assets = (release_data or {}).get('assets', {}) or {}
resolved = []
missing = []
for package_name in DEBIAN_PACKAGES:
filename = _match_debian_asset(assets, package_name)
if filename:
info = assets[filename]
resolved.append((filename, info['url'], info['hash']))
else:
missing.append(package_name)
if not missing:
return resolved
# Fall back to a local directory.
logging.warning(
"Release %s has no .deb assets for: %s; looking in %s",
(release_data or {}).get('tag_name', '<unknown>'),
", ".join(missing),
DEBIAN_FALLBACK_DIR,
)
fallback = {}
if os.path.isdir(DEBIAN_FALLBACK_DIR):
for entry in sorted(os.listdir(DEBIAN_FALLBACK_DIR)):
if entry.lower().endswith(".deb"):
fallback[entry] = os.path.join(DEBIAN_FALLBACK_DIR, entry)
if not fallback:
raise Exception(
"No .deb assets for %s in the latest release, and %s contains no .deb files. "
"Upload icaclient_<version>_amd64.deb and ctxusb_<version>_amd64.deb to the "
"release, or set VDI_DEB_DIR to a directory holding them."
% (", ".join(missing), DEBIAN_FALLBACK_DIR)
)
# Rebuild the list, substituting fallback files for whatever was missing.
resolved = []
for package_name in DEBIAN_PACKAGES:
filename = _match_debian_asset(assets, package_name)
if filename:
info = assets[filename]
resolved.append((filename, info['url'], info['hash']))
continue
local_name = _match_debian_asset(fallback, package_name)
if not local_name:
raise Exception(
"No %s*.deb found in the release or in %s. Found there: %s"
% (package_name, DEBIAN_FALLBACK_DIR, sorted(fallback) or "nothing")
)
logging.info("Using local file %s for %s", fallback[local_name], package_name)
resolved.append((local_name, fallback[local_name], None))
return resolved
def build_debian_index(repo_dir):
"""Generate Packages/Packages.gz/Release for a flat apt repository.
A flat ("trivial") archive is the apt equivalent of the single-directory
createrepo repository on the Fedora side: no dists/ tree, and apt reads it
with ``deb [trusted=yes] file:/var/local/citrix-repo ./``.
"""
packages_path = os.path.join(repo_dir, "Packages")
release_path = os.path.join(repo_dir, "Release")
with open(packages_path, "wb") as handle:
result = subprocess.run(
["apt-ftparchive", "packages", "."],
cwd=repo_dir, stdout=handle, stderr=subprocess.PIPE,
)
if result.returncode != 0:
raise Exception(
"apt-ftparchive packages failed: %s"
% result.stderr.decode(errors="replace").strip()
)
# apt ignores an uncompressed Packages file only for file:// sources; ship
# the gzip as well so the repository also works over http if it is ever
# exported.
with open(packages_path, "rb") as source, open(packages_path + ".gz", "wb") as target:
import gzip
with gzip.GzipFile(fileobj=target, mode="wb", mtime=0) as gz:
shutil.copyfileobj(source, gz)
with open(release_path, "wb") as handle:
result = subprocess.run(
[
"apt-ftparchive",
"-o", "APT::FTPArchive::Release::Origin=REYHER",
"-o", "APT::FTPArchive::Release::Label=Citrix Local Repository",
"-o", "APT::FTPArchive::Release::Suite=trixie",
"-o", "APT::FTPArchive::Release::Codename=trixie",
"-o", "APT::FTPArchive::Release::Architectures=amd64",
"-o", "APT::FTPArchive::Release::Description=Locally built Citrix Workspace packages",
"release", ".",
],
cwd=repo_dir, stdout=handle, stderr=subprocess.PIPE,
)
if result.returncode != 0:
raise Exception(
"apt-ftparchive release failed: %s"
% result.stderr.decode(errors="replace").strip()
)
if os.path.getsize(packages_path) == 0:
raise Exception("apt-ftparchive produced an empty Packages file in %s" % repo_dir)
def sync_debian(is_newer, release_data):
repo_ready = local_repo_is_populated()
if not is_newer and repo_ready:
logging.info("Skipping download; no new release available.")
return
if not is_newer and not repo_ready:
logging.info("No newer release, but %s has no package index; rebuilding.", LOCAL_REPO_DIR)
if release_data is None:
# Reached when the release was unchanged but the repository is missing.
release_data = fetch_release_info(REPO_OWNER, REPO_NAME)
packages = resolve_debian_packages(release_data)
os.makedirs(STAGING_DIR, exist_ok=True)
os.makedirs(LOCAL_REPO_DIR, exist_ok=True)
# Remove every .deb from the published directory before repopulating it.
#
# The Fedora path writes fixed filenames (ctxusb.rpm, ICAClient.rpm), so a
# new release overwrites the old files and the repository can never hold two
# versions. Debian package filenames embed the version, so copying alone
# would leave every previous version behind; `apt-ftparchive packages .`
# would then index all of them and apt would always pick the highest, making
# a rollback impossible. Deleting first reproduces the Fedora guarantee.
for entry in os.listdir(LOCAL_REPO_DIR):
if entry.lower().endswith(".deb"):
stale = os.path.join(LOCAL_REPO_DIR, entry)
try:
os.remove(stale)
logging.info("Removed stale package %s", entry)
except OSError as error:
logging.warning("Could not remove stale package %s: %s", stale, error)
for filename, source, expected_hash in packages:
staged = os.path.join(STAGING_DIR, filename)
if os.path.exists(source):
# Already a local file (fallback directory).
logging.info("Copying %s into the staging area", source)
if os.path.abspath(source) != os.path.abspath(staged):
shutil.copyfile(source, staged)
else:
if os.path.exists(staged):
os.remove(staged)
download_file(source, staged, expected_hash)
published = os.path.join(LOCAL_REPO_DIR, filename)
logging.info("Copying %s...", filename)
shutil.copyfile(staged, published)
logging.info("Finished copying %s", filename)
logging.info("Building the local apt repository index...")
build_debian_index(LOCAL_REPO_DIR)
logging.info("Finished building the local apt repository index")
# The apt source file. trusted=yes is deliberate: this repository is
# generated on the machine from packages this script just fetched and
# verified, so there is no second party to authenticate against. See
# README.md for the reasoning.
logging.info("Copying local-citrix-repo.list...")
sources_src = _repo_file("local-citrix-repo.list")
try:
shutil.copyfile(sources_src, DEBIAN_SOURCES_PATH)
except OSError as error:
# Never let a missing file stop the repository from being usable: write
# the canonical line instead and say so.
logging.warning("Could not copy %s (%s); writing the source line directly", sources_src, error)
with open(DEBIAN_SOURCES_PATH, "w") as handle:
handle.write("# Local Citrix repository (generated by update_local_repo.py)\n")
handle.write(DEBIAN_SOURCES_LINE + "\n")
logging.info("Finished copying local-citrix-repo.list")
subprocess.run(["apt-get", "update"], check=False)
if shutil.which("pkcon"):
subprocess.run(["pkcon", "refresh", "force"], check=False)
save_last_release(release_data)
# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------
def main():
logging.info("Detected package family: %s", PACKAGE_FAMILY)
# Update the local repository via git pull before proceeding
try:
subprocess.run(['git', 'pull'], check=True, capture_output=True)
logging.info("Updated repo via git pull")
except subprocess.CalledProcessError as e:
logging.warning(f"Git pull failed (non-zero exit): {e}")
except FileNotFoundError:
logging.warning("Git not found; skipping pull")
except Exception as e:
logging.warning(f"Unexpected error during git pull: {e}")
# Apply the standard KDE Plasma settings. This also installs the per-session
# helper used by the XDG autostart entry, and updates users who are currently
# logged in. Keep this before the release download so the settings are applied
# even if the Citrix repository update fails.
try:
from configure_kde import apply_all as apply_kde_settings
apply_kde_settings()
except Exception as e:
logging.exception(f"Failed to apply KDE settings: {e}")
install_desktop_shortcuts()
# Debian needs a polkit rule before a desktop user can update without a
# password, and the offline-update timer. Both are idempotent and are done
# here, not in the preseed, so existing machines pick them up on the next
# cron run - the same way configure_kde.py back-fills older installs.
install_debian_update_policy()
is_newer, release_data = is_newer_release(REPO_OWNER, REPO_NAME)
if PACKAGE_FAMILY == "debian":
sync_debian(is_newer, release_data)
else:
sync_fedora(is_newer, release_data)
print("All files processed successfully!")
return 0
if __name__ == "__main__":
raise SystemExit(main())