feat: provision Chrome and DVD codecs without a manual step

A fresh classroom needed two things installed by hand on every box:
Google Chrome, which is not in Debian, and the DVD codecs, which Debian
cannot ship. Both now happen on their own.

ekklesia-classroom-provision.service runs after every boot and does the
work that needs the network and the apt lock, neither of which a package
postinst can have. Each step returns immediately if it is already done,
so a provisioned machine costs nothing and a machine that was offline
the first time gets another go at the next boot. Nothing there is
allowed to fail the boot: a classroom with no DVD codecs is still a
working classroom, and it says so in the log rather than silently.

The postinst enables the service but deliberately does not start it.
Every OTA update reboots the moment the install finishes, and an apt run
killed by that reboot would leave dpkg half-configured.

Chrome comes from Google's own repository rather than a one-off .deb, so
it keeps getting security updates. Google's package migrates whatever we
write into a deb822 file of its own, so the repository is looked for
across every source file instead of only the one we would write;
otherwise a machine that had Chrome removed would end up with two copies
of the same repository.

The DVD codec helper previously assumed deb822 sources and did nothing
on a machine using a classic /etc/apt/sources.list, which is what the
hardware actually runs. It now handles both formats, and only ever adds
a missing component to an existing Debian entry — so it cannot produce a
duplicate repository or a duplicate component however many times it
runs, and third-party repositories like Chrome's are never touched. It
also answers libdvd-pkg's debconf questions, so nothing blocks on a
prompt in a service with no terminal.

Tested against fixture APT trees for classic sources.list, deb822
.sources, contrib already enabled, repeated runs, third-party
repositories and the awkward real lines: bracketed options, indentation,
trailing comments and flat repositories.

Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
ekklesia
2026-09-04 21:33:44 -05:00
co-authored by Claude Opus 5
parent c81fc1b0b9
commit a3dba6e8fb
10 changed files with 858 additions and 52 deletions
+89
View File
@@ -0,0 +1,89 @@
#!/bin/bash
set -uo pipefail
# Installs Google Chrome from Google's own APT repository.
#
# Chrome is not in Debian, and a classroom is not usable without it, so
# a fresh machine provisions it itself rather than waiting for someone to
# install it by hand on every box. Using the repository rather than a
# one-off .deb means Chrome keeps getting security updates.
#
# sudo classroom-chrome-setup
#
# Idempotent: once Chrome is installed this returns immediately.
KEYRING=/etc/apt/keyrings/google-chrome.gpg
# The same path Google's own package manages, so the two cannot end up
# as two copies of the same repository.
LIST=/etc/apt/sources.list.d/google-chrome.list
REPOSITORY="https://dl.google.com/linux/chrome/deb/"
KEY_URL="https://dl.google.com/linux/linux_signing_key.pub"
log() {
echo "[classroom-chrome-setup] $1"
}
if command -v google-chrome >/dev/null 2>&1; then
log "Google Chrome is already installed; nothing to do"
exit 0
fi
if [[ "$(id -u)" -ne 0 ]]; then
log "must be run as root: sudo classroom-chrome-setup"
exit 1
fi
install -d -m 0755 /etc/apt/keyrings
if [[ ! -s "$KEYRING" ]]; then
log "fetching Google's signing key"
if ! curl -fsS --retry 3 --max-time 60 "$KEY_URL" |
gpg --dearmor --batch --yes --output "$KEYRING.new"; then
rm -f "$KEYRING.new"
log "could not fetch Google's signing key; is this machine online?"
exit 1
fi
chmod 0644 "$KEYRING.new"
mv "$KEYRING.new" "$KEYRING"
fi
# Google's own package migrates whatever we write here into a deb822
# /etc/apt/sources.list.d/google-chrome.sources of its own, so look for
# the repository everywhere rather than only in the file we would write.
# Otherwise a machine that has had Chrome removed would end up with two
# copies of the same repository.
if ! grep -rqsF "dl.google.com/linux/chrome" \
/etc/apt/sources.list /etc/apt/sources.list.d/; then
log "adding the Google Chrome repository"
printf 'deb [arch=amd64 signed-by=%s] %s stable main\n' \
"$KEYRING" "$REPOSITORY" > "$LIST"
chmod 0644 "$LIST"
else
log "the Google Chrome repository is already configured"
fi
export DEBIAN_FRONTEND=noninteractive
# The OTA install or the update timer may hold the lock; wait it out
# rather than failing the whole provisioning run.
APT=(apt-get -o DPkg::Lock::Timeout=600)
log "updating package lists"
if ! "${APT[@]}" update; then
log "apt-get update failed; is this machine online?"
exit 1
fi
log "installing google-chrome-stable"
if ! "${APT[@]}" install -y google-chrome-stable; then
log "could not install Google Chrome"
exit 1
fi
log "Google Chrome installed"
+402 -50
View File
@@ -1,61 +1,413 @@
#!/bin/bash
set -euo pipefail
#!/usr/bin/env python3
# One-time bootstrap for encrypted (commercial) DVD-Video playback.
#
# Most retail DVDs are CSS encrypted. Debian cannot ship the decryption
# library, so libdvdcss has to be built on the machine from the contrib
# package libdvd-pkg. This is deliberately NOT run from the package
# postinst: it needs the network, it compiles a package, and it must not
# run while dpkg already holds the apt lock during an OTA update.
#
# Run this once, as root, on any classroom that needs commercial discs:
#
# sudo classroom-dvd-css-setup
#
# Unencrypted discs (church curriculum, home-burned video) play without it.
"""Enable encrypted (commercial) DVD-Video playback.
if [[ "$(id -u)" -ne 0 ]]; then
echo "classroom-dvd-css-setup must be run as root." >&2
exit 1
fi
Most retail discs are CSS encrypted. Debian cannot ship the decryption
library, so libdvdcss has to be built on the machine from the contrib
package libdvd-pkg. That needs the contrib component enabled, which this
does for either APT source format:
if [[ -e /usr/lib/x86_64-linux-gnu/libdvdcss.so.2 ]]; then
echo "libdvdcss is already installed. Nothing to do."
exit 0
fi
classic /etc/apt/sources.list and /etc/apt/sources.list.d/*.list
deb http://deb.debian.org/debian/ trixie main non-free-firmware
echo "Enabling the Debian contrib component..."
deb822 /etc/apt/sources.list.d/*.sources
Components: main non-free-firmware
if ! grep -rqs 'contrib' /etc/apt/sources.list /etc/apt/sources.list.d/; then
if [[ -f /etc/apt/sources.list.d/debian.sources ]]; then
sed -i 's/^\(Components:.*\)$/\1 contrib/' \
/etc/apt/sources.list.d/debian.sources
else
echo "Could not find a Debian sources file to add contrib to." >&2
echo "Add 'contrib' manually and re-run this script." >&2
exit 1
fi
fi
Only existing Debian entries are edited, and only by adding the missing
component, so running this repeatedly cannot produce a duplicate
repository or a duplicate component.
echo "Installing libdvd-pkg..."
sudo classroom-dvd-css-setup # set this machine up now
classroom-dvd-css-setup --status # report without changing anything
export DEBIAN_FRONTEND=noninteractive
Unencrypted discs — church curriculum, home-burned video — play without
any of this.
"""
apt-get update
apt-get install -y libdvd-pkg
import argparse
import os
import re
import subprocess
import sys
from pathlib import Path
echo "Building libdvdcss..."
sys.path.insert(0, "/usr/local/lib/ekklesia-classroom")
sys.path.insert(
0,
os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "lib"),
)
# libdvd-pkg downloads and builds libdvdcss during reconfigure.
dpkg-reconfigure -f noninteractive libdvd-pkg
from classroom_config import enabled, read_device_config # noqa: E402
if [[ -e /usr/lib/x86_64-linux-gnu/libdvdcss.so.2 ]]; then
echo
echo "libdvdcss installed. Commercial DVDs should now play."
echo "Test with an actual disc before relying on it."
else
echo
echo "libdvdcss was not installed. Commercial discs will not play." >&2
exit 1
fi
# Tests point this at a fixture tree instead of the live system.
APT_ROOT = Path(os.environ.get("CLASSROOM_APT_ROOT", "/"))
COMPONENT = "contrib"
# A Debian entry is one served from debian.org or from a path with a
# /debian segment, which covers local mirrors. Deliberately narrow: the
# Google Chrome repository must never be touched.
DEBIAN_URI = re.compile(
r"^\w+://[^/]*debian\.org(/|$)|^\w+://[^/]*/[^ ]*\bdebian\b",
re.IGNORECASE,
)
CLASSIC_LINE = re.compile(
r"^(?P<indent>\s*)"
r"(?P<type>deb|deb-src)"
r"(?P<options>\s+\[[^\]]*\])?"
r"(?P<gap>\s+)"
r"(?P<body>[^#]*?)"
r"(?P<comment>\s*#.*)?$"
)
def log(message):
print(f"[classroom-dvd-css-setup] {message}", flush=True)
def sources_list():
return APT_ROOT / "etc/apt/sources.list"
def sources_directory():
return APT_ROOT / "etc/apt/sources.list.d"
def is_debian(uri):
return bool(DEBIAN_URI.match(uri))
def rewrite_classic(text):
"""Add contrib to Debian entries in a classic sources.list.
Returns the new text, whether anything changed, and whether a Debian
entry already carried the component.
"""
lines = text.splitlines(keepends=True)
changed = False
present = False
for index, line in enumerate(lines):
ending = "\n" if line.endswith("\n") else ""
match = CLASSIC_LINE.match(line.rstrip("\n"))
if not match:
continue
fields = match.group("body").split()
# uri, suite, then one or more components. A flat repository
# (no components) has nothing to add.
if len(fields) < 3:
continue
uri = fields[0]
components = fields[2:]
if not is_debian(uri):
continue
if COMPONENT in components:
present = True
continue
if "main" not in components:
continue
components.append(COMPONENT)
lines[index] = "".join(
[
match.group("indent"),
match.group("type"),
match.group("options") or "",
match.group("gap"),
" ".join([uri, fields[1]] + components),
match.group("comment") or "",
ending,
]
)
changed = True
return "".join(lines), changed, present
def rewrite_deb822(text):
"""Add contrib to the Components of Debian stanzas in a .sources file.
Returns the new text, whether anything changed, and whether a Debian
stanza already carried the component.
"""
lines = text.splitlines(keepends=True)
changed = False
present = False
# Stanza boundaries are blank lines.
stanza_start = 0
stanzas = []
for index, line in enumerate(lines + ["\n"]):
if line.strip():
continue
if index > stanza_start:
stanzas.append((stanza_start, index))
stanza_start = index + 1
for start, end in stanzas:
uris = None
components_index = None
for index in range(start, end):
field, separator, value = lines[index].partition(":")
if not separator:
continue
key = field.strip().lower()
if key == "uris":
uris = value.split()
elif key == "components":
components_index = index
if components_index is None or not uris:
continue
if not any(is_debian(uri) for uri in uris):
continue
field, _, value = lines[components_index].partition(":")
components = value.split()
if COMPONENT in components:
present = True
continue
if "main" not in components:
continue
components.append(COMPONENT)
ending = "\n" if lines[components_index].endswith("\n") else ""
lines[components_index] = f"{field}: {' '.join(components)}{ending}"
changed = True
return "".join(lines), changed, present
def source_files():
"""Every APT source file, newest format first."""
found = []
directory = sources_directory()
if directory.is_dir():
found.extend(sorted(directory.glob("*.sources")))
found.extend(sorted(directory.glob("*.list")))
if sources_list().is_file():
found.append(sources_list())
return found
def enable_contrib():
"""Enable contrib in the existing Debian sources. Idempotent."""
touched = []
for path in source_files():
try:
original = path.read_text()
except OSError as error:
log(f"skipping {path}: {error}")
continue
if path.suffix == ".sources":
updated, changed, _ = rewrite_deb822(original)
else:
updated, changed, _ = rewrite_classic(original)
if not changed:
continue
path.write_text(updated)
touched.append(path)
if touched:
for path in touched:
log(f"enabled {COMPONENT} in {path}")
else:
log(f"{COMPONENT} was already enabled")
return touched
def contrib_available():
"""True when some Debian entry already carries the contrib component."""
for path in source_files():
try:
text = path.read_text()
except OSError:
continue
if path.suffix == ".sources":
_, _, present = rewrite_deb822(text)
else:
_, _, present = rewrite_classic(text)
if present:
return True
return False
def libdvdcss_installed():
# ldconfig lives in /sbin, which is not on an ordinary user's PATH.
for candidate in ("/sbin/ldconfig", "/usr/sbin/ldconfig", "ldconfig"):
try:
result = subprocess.run(
[candidate, "-p"],
capture_output=True,
text=True,
)
except OSError:
continue
return "libdvdcss.so.2" in result.stdout
return any(
Path(directory, "libdvdcss.so.2").exists()
for directory in ("/usr/lib/x86_64-linux-gnu", "/usr/lib", "/lib")
)
def apt(*arguments):
environment = dict(os.environ)
environment["DEBIAN_FRONTEND"] = "noninteractive"
return subprocess.run(
[
"apt-get",
# An OTA install or the update timer may hold the lock.
# Waiting is far better than failing the provisioning run.
"-o",
"DPkg::Lock::Timeout=600",
*arguments,
],
env=environment,
).returncode
def preseed():
"""Answer libdvd-pkg's debconf questions so nothing blocks on a prompt."""
answers = "\n".join(
[
"libdvd-pkg libdvd-pkg/build boolean true",
"libdvd-pkg libdvd-pkg/post-invoke_hook-install boolean true",
"libdvd-pkg libdvd-pkg/post-invoke_hook-remove boolean true",
]
)
subprocess.run(
["debconf-set-selections"],
input=answers + "\n",
text=True,
)
def install():
log("updating package lists")
if apt("update") != 0:
log("apt-get update failed; is this machine online?")
return 1
preseed()
log("installing libdvd-pkg")
if apt("install", "-y", "libdvd-pkg") != 0:
log("could not install libdvd-pkg")
return 1
log("building libdvdcss")
environment = dict(os.environ)
environment["DEBIAN_FRONTEND"] = "noninteractive"
subprocess.run(
["dpkg-reconfigure", "-f", "noninteractive", "libdvd-pkg"],
env=environment,
)
if not libdvdcss_installed():
log("libdvdcss was not built; commercial discs will not play")
return 1
log("libdvdcss installed; commercial discs should now play")
return 0
def status():
print(f"contrib enabled: {contrib_available()}")
print(f"libdvdcss: {'installed' if libdvdcss_installed() else 'missing'}")
config = read_device_config()
print(f"DVD_ENABLED: {enabled(config, 'DVD_ENABLED', False)}")
return 0 if libdvdcss_installed() else 1
def main():
parser = argparse.ArgumentParser(
description="Enable commercial DVD playback on this classroom.",
)
parser.add_argument(
"--status",
action="store_true",
help="Report the current state without changing anything",
)
parser.add_argument(
"--enable-contrib-only",
action="store_true",
help="Only enable the contrib component, install nothing",
)
parser.add_argument(
"--if-enabled",
action="store_true",
help="Do nothing unless DVD_ENABLED is set for this classroom",
)
arguments = parser.parse_args()
if arguments.status:
return status()
if arguments.if_enabled:
if not enabled(read_device_config(), "DVD_ENABLED", False):
log("DVD support is not enabled on this classroom; nothing to do")
return 0
# Only the real system needs privilege. Pointed at a fixture tree
# through CLASSROOM_APT_ROOT, this is just a file rewrite.
if APT_ROOT == Path("/") and os.geteuid() != 0:
log("must be run as root: sudo classroom-dvd-css-setup")
return 1
if arguments.enable_contrib_only:
enable_contrib()
return 0
if libdvdcss_installed():
log("libdvdcss is already installed; nothing to do")
return 0
enable_contrib()
return install()
if __name__ == "__main__":
sys.exit(main())
+41
View File
@@ -0,0 +1,41 @@
#!/bin/bash
set -uo pipefail
# Finishes setting a classroom machine up: the things that need the
# network and the apt lock, and so cannot run from the package postinst.
#
# Run from ekklesia-classroom-provision.service at every boot. Each step
# checks whether it is already done and returns immediately if so, so a
# provisioned machine costs nothing, and a machine that was offline the
# first time gets another go at the next boot.
#
# Nothing here is allowed to fail the boot. A classroom with no DVD
# codecs is still a working classroom.
log() {
echo "[classroom-provision] $1"
}
log "starting"
if /usr/local/bin/classroom-chrome-setup; then
:
else
log "WARNING: Google Chrome is not installed. The Browser button will"
log "WARNING: not work until this succeeds. Retrying at the next boot,"
log "WARNING: or run: sudo classroom-chrome-setup"
fi
# DVD codecs are only fetched for rooms that actually have a drive.
if /usr/local/bin/classroom-dvd-css-setup --if-enabled; then
:
else
log "WARNING: commercial DVD support is not set up. Unencrypted discs"
log "WARNING: still play. Retrying at the next boot, or run:"
log "WARNING: sudo classroom-dvd-css-setup"
fi
log "finished"
# Provisioning is best-effort by design.
exit 0