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.
This commit is contained in:
Mistercoolertyper committed 2026-11-04 09:24:57 +01:00
1 parent 5d9b278270
commit 6ddb1d251a
6 files changed
+2566 -64

No files matched your search

+263
View File
@@ -1 +1,264 @@
# 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`.
## 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.
+535
View File
@@ -0,0 +1,535 @@
#_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, used by /root/auto_update.sh.
# 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
# systemd-inhibit --what=sleep:idle --who="Auto Update Script" --why="Downloading system updates" /bin/bash -c "
# pkcon refresh force
# pkcon update --only-download
# if pkcon offline-get-prepared >/dev/null 2>&1; then
# pkcon offline-trigger
# fi
# "
# 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"
# 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.
# * `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' 'systemd-inhibit --what=sleep:idle --who="Auto Update Script" --why="Downloading system updates" /bin/bash -c "' ' pkcon refresh force' ' pkcon update --only-download' ' if pkcon offline-get-prepared >/dev/null 2>&1; then' ' pkcon offline-trigger' ' fi' '"' '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"' '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.
+255
View File
@@ -0,0 +1,255 @@
# 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 |
| T15 | Nothing was left behind: no source file, no cached indexes, no installs, no `__pycache__` |
### 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.
## 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.
## 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.
## 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.
+1002
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 ./
+490 -64
View File
@@ -1,49 +1,169 @@
#!/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
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}")
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
# 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}")
REPO_OWNER = "REYHER-Systemtechnik-Public"
REPO_NAME = "VDI-Linux"
api_base = "https://nachos386.lcube-server.de/api/v1"
API_BASE = "https://nachos386.lcube-server.de/api/v1"
import os
import subprocess
import pwd
# Where downloaded packages are staged before being published.
STAGING_DIR = "/temp/packages"
LAST_RELEASE_FILE = os.path.join(STAGING_DIR, "last_release.json")
for user in os.listdir("/home"):
# 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:
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")
tokens = set((ident + " " + like).split())
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):
@@ -66,9 +186,22 @@ for user in os.listdir("/home"):
os.chmod(script, 0o755)
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"
# ---------------------------------------------------------------------------
# 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())
@@ -81,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}")
@@ -98,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.")
@@ -118,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()
@@ -133,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)
@@ -160,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:
@@ -215,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)
@@ -259,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())}")
@@ -287,37 +435,315 @@ 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}")
else:
logging.info("Skipping download; no new release available.")
save_last_release(release_data)
print("All files processed successfully!")
# ---------------------------------------------------------------------------
# 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
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()
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())