#!/bin/bash

#sanity check

if [ $# -lt 1 ] ; then
	echo "usage $0 ROOTDIR"
	exit 1
fi

rootdir=$1

if [ -z "$rootdir" ]; then
	echo "ROOTDIR is not set."
	exit 1
fi

# Check root directory
if [ ! -d $rootdir ]; then
	echo "$rootdir: should be a directory."
	exit 1
fi

pushd $rootdir > /dev/null

[ -f etc/localtime ] && rm -f etc/localtime
ln -s ../usr/share/zoneinfo/Host etc/localtime
cp -fp /etc/localtime usr/share/zoneinfo/Host

popd > /dev/null

##############################################################################
# PSBM-163587: keep the systemd family on noble (255.x).
#
# Ubuntu 26.04 ships systemd 259; systemd >= 258 removed cgroup v1 support
# and the vz7 kernel (3.10) is cgroup-v1-only, so stock resolute systemd
# exits at boot ("Failed to mount API filesystems", rc 255).  systemd 255
# from noble boots fine on cgroup v1 and is security-maintained by Canonical
# until 2029 (ESM 2034).
#
# This block runs on the HN at cache time (vztt post-cache, VE0 context):
# it writes a permanent apt pin into the CT so the systemd family always
# follows noble, then chroots into the fresh cache and downgrades the
# already-installed resolute systemd to noble's version.  vztt's cache-time
# apt uses its own generated config and ignores in-root pins, which is why
# the downgrade has to happen here rather than during package installation.
##############################################################################

NOBLE_SYSTEMD_PKGS="systemd systemd-sysv systemd-dev systemd-resolved systemd-timesyncd libsystemd0 libsystemd-shared libpam-systemd libnss-systemd libudev1 udev"

mkdir -p $rootdir/etc/apt/sources.list.d $rootdir/etc/apt/preferences.d

cat > $rootdir/etc/apt/sources.list.d/vz-noble-systemd.list << EOF
# Virtuozzo: systemd is held at the noble (cgroup-v1 capable) version.
# See /etc/apt/preferences.d/99-vz-systemd-pin.  PSBM-163587
deb http://archive.ubuntu.com/ubuntu noble main
deb http://archive.ubuntu.com/ubuntu noble-updates main
deb http://security.ubuntu.com/ubuntu noble-security main
EOF

cat > $rootdir/etc/apt/preferences.d/99-vz-systemd-pin << EOF
# Virtuozzo VHS7: the vz7 kernel supports only cgroup v1; systemd >= 258
# removed cgroup v1 support and cannot boot in this container.  The systemd
# family is pinned to Ubuntu noble (255.x, maintained until 2029) and keeps
# receiving noble security updates through this pin.  Do not remove, or the
# container will not boot after the next systemd upgrade.  PSBM-163587
Package: $NOBLE_SYSTEMD_PKGS
Pin: release n=noble*
Pin-Priority: 1001

Package: *
Pin: release n=noble*
Pin-Priority: -10
EOF

# --- resolve and download the noble systemd debs (all HN-side, no chroot) --
# Running apt inside the cache-root chroot from the HN is unreliable on the
# vz7 kernel (apt 3.x segfaults building its cache there), so package
# resolution and download happen on the HN, and the dpkg transaction runs
# in the temp CT via vzctl exec2 - the same mechanism vztt itself uses for
# the post-install script.
ctid=$2
if [ -z "$ctid" ]; then
	echo "PSBM-163587: no CTID passed to post-cache, cannot run in-CT downgrade."
	exit 1
fi

UBU=http://archive.ubuntu.com/ubuntu
DL=$rootdir/var/cache/vz-noble-systemd
mkdir -p $DL

# PSBM-163587: on proxy-only nodes, honor the node proxy configuration
# (vztt.conf HTTP_PROXY) for the HN-side downloads below - curl does not
# read vztt.conf by itself.
VZTT_HTTP_PROXY=$(sed -n 's/^HTTP_PROXY=//p' /etc/vztt/vztt.conf 2>/dev/null | tr -d '"' | head -1)
if [ -n "$VZTT_HTTP_PROXY" ]; then
	export http_proxy="$VZTT_HTTP_PROXY" https_proxy="$VZTT_HTTP_PROXY"
fi

urls=/tmp/vz-noble-urls.$$
for pocket in noble noble-updates noble-security; do
	curl -s --max-time 120 $UBU/dists/$pocket/main/binary-amd64/Packages.xz | xz -d
done | awk -v pkgs="$NOBLE_SYSTEMD_PKGS" '
	BEGIN { n = split(pkgs, a, " "); for (i = 1; i <= n; i++) want[a[i]] = 1 }
	/^Package: / { p = $2 }
	/^Version: / { v = $2 }
	/^Filename: / { if (want[p]) print p, v, $2 }
' | sort -k1,1 -k2,2V | awk '{ best[$1] = $3 } END { for (p in best) print p, best[p] }' > $urls

if [ ! -s $urls ]; then
	echo "PSBM-163587: failed to resolve noble systemd packages from $UBU."
	rm -f $urls
	exit 1
fi

# Keep only the family members actually present in the cache (dpkg database
# is a plain file - read it directly, no execution inside the root needed).
while read p f; do
	if grep -q "^Package: $p$" $rootdir/var/lib/dpkg/status; then
		curl -s --max-time 300 -o $DL/$(basename $f) $UBU/$f || {
			echo "PSBM-163587: download failed: $UBU/$f"; rm -f $urls; exit 1; }
	fi
done < $urls
rm -f $urls

if ! ls $DL/systemd_255* > /dev/null 2>&1; then
	echo "PSBM-163587: noble systemd deb missing after download."
	exit 1
fi

# --- run the downgrade inside the temp CT ----------------------------------
# systemd-cryptsetup has no noble counterpart (and is useless in a CT).
if grep -q "^Package: systemd-cryptsetup$" $rootdir/var/lib/dpkg/status; then
	vzctl exec2 $ctid "dpkg --purge --force-depends systemd-cryptsetup" || exit 1
fi

# PSBM-163587: resolute's current glibc (libc6 2.42-2ubuntu5) declares
# "Breaks: systemd (<< 256~rc4-1~)", so a plain dpkg refuses to configure the
# noble 255.x systemd we require (the vz7 kernel is cgroup-v1 only and systemd
# >= 258 dropped cgroup v1).  The noble 255.x systemd is runtime-proven on this
# userspace (boot + full CT lifecycle + apps), so we override the conservative
# Breaks with --force-breaks; --force-depends-version clears the version-exact
# Depends among the family members (systemd-sysv/-resolved require systemd = the
# same version) while they configure together in one transaction.
DPKG_FORCE="--force-breaks --force-depends-version"
vzctl exec2 $ctid "dpkg -i --auto-deconfigure $DPKG_FORCE /var/cache/vz-noble-systemd/*.deb" || {
	echo "PSBM-163587: in-CT dpkg downgrade to noble systemd FAILED."
	exit 1
}
vzctl exec2 $ctid "dpkg --configure -a $DPKG_FORCE" || exit 1
vzctl exec2 $ctid "rm -rf /var/cache/vz-noble-systemd"

# Fail the cache loudly if PID 1 is not the cgroup-v1-capable systemd.
if ! vzctl exec2 $ctid "/usr/lib/systemd/systemd --version" | grep -q "^systemd 255"; then
	echo "PSBM-163587: systemd downgrade to noble 255.x FAILED - the cache would not boot on the vz7 kernel."
	exit 1
fi

echo "PSBM-163587: systemd pinned to noble 255.x for cgroup v1 compatibility."

# --- freeze the systemd family with a dpkg-level hold ------------------------
# vztt's `vzpkg update` path generates its own apt config and ignores the in-CT
# preferences pin above, so without this it would try to pull resolute systemd
# 259 (which cannot run on the vz7 kernel) and fail the whole update.  apt-mark
# hold lives in the CT's dpkg database, which that path DOES honor, so the
# family is kept back and the update completes.  Trade-off: this also freezes
# systemd against in-CT `apt upgrade`; systemd security updates for CTs then
# require an explicit `apt-mark unhold`+upgrade or a refreshed template.
vzctl exec2 $ctid "for p in $NOBLE_SYSTEMD_PKGS; do dpkg -s \$p >/dev/null 2>&1 && apt-mark hold \$p; done" || true
echo "PSBM-163587: systemd family held (vzpkg update keeps noble 255.x)."

##############################################################################
# PSBM-163587: make the pinned systemd 255 tolerate the systemd>=256 sysusers.d
# "!" type-modifier that resolute packages ship (mariadb: "u! mysql ...";
# mysql-server and others too).  255's systemd-sysusers aborts on "Unknown
# modifier 'u!'", breaking those packages' postinst.  We divert systemd-sysusers
# to a wrapper that strips the modifier (a no-op inside a running CT) before the
# real binary parses the files.  Diverted so it survives systemd security
# updates; systemic so it covers every current and future package, not just
# mariadb.  (The long-term platform fix is to backport "!"-tolerance into the
# pinned systemd-sysusers itself; this ships in the template meanwhile.)
##############################################################################
cat > $rootdir/usr/local/sbin/vz-sysusers-compat << 'VZSYSUSERS'
#!/bin/sh
# PSBM-163587: strip systemd>=256 sysusers.d "!" type-modifier for pinned 255.
for d in /usr/lib/sysusers.d /usr/local/lib/sysusers.d /etc/sysusers.d /run/sysusers.d; do
	[ -d "$d" ] || continue
	for f in "$d"/*.conf; do
		[ -e "$f" ] || continue
		sed -i 's/^\([[:space:]]*[ugmr]\)![[:space:]]/\1 /' "$f" 2>/dev/null || true
	done
done
exec /usr/bin/systemd-sysusers.vzreal "$@"
VZSYSUSERS
chmod 0755 $rootdir/usr/local/sbin/vz-sysusers-compat

vzctl exec2 $ctid "dpkg-divert --quiet --add --rename --divert /usr/bin/systemd-sysusers.vzreal /usr/bin/systemd-sysusers && install -m 0755 /usr/local/sbin/vz-sysusers-compat /usr/bin/systemd-sysusers" || {
	echo "PSBM-163587: failed to install systemd-sysusers compat wrapper."
	exit 1
}

# Retroactively fix any sysusers.d file already shipped in the cache, so the
# base image is clean even before the wrapper is first invoked.
vzctl exec2 $ctid "for f in /usr/lib/sysusers.d/*.conf; do [ -e \"\$f\" ] && sed -i 's/^\\([[:space:]]*[ugmr]\\)![[:space:]]/\\1 /' \"\$f\"; done" || true

echo "PSBM-163587: systemd-sysusers compat wrapper installed (v256 '!' modifier)."

##############################################################################
# PSBM-163587: ship an on-demand systemd security-refresh helper in the image.
# The systemd family is held at noble 255.x (the vz7 kernel is cgroup-v1 only;
# resolute systemd 259 cannot boot here), so `apt upgrade`/`vzpkg update` keep
# it back and its security updates are not applied automatically.  This helper
# lets an administrator pull the latest *noble* 255.x systemd security build on
# demand: it unholds the family, installs the newest noble 255.x (forcing past
# resolute glibc's "Breaks: systemd (<< 256~rc4-1~)"), then re-holds.  It refuses
# to install anything that is not 255.x, so it can never pull the unbootable 259.
##############################################################################
cat > $rootdir/usr/local/sbin/vz-refresh-systemd << 'VZREFRESH'
#!/bin/bash
# PSBM-163587: refresh the pinned noble systemd family to the latest noble
# 255.x security build.  systemd >= 256 dropped cgroup v1 and cannot run on the
# VHS7 (vz7) kernel, so this container keeps the systemd family on noble 255.x.
# Run this when you want to apply noble systemd security updates.  Do NOT let
# systemd upgrade to the Ubuntu 26.04 (259) version - the container will not boot.
set -e

FAMILY="systemd systemd-sysv systemd-dev systemd-resolved systemd-timesyncd libsystemd0 libsystemd-shared libpam-systemd libnss-systemd libudev1 udev"

[ "$(id -u)" = 0 ] || { echo "vz-refresh-systemd: must run as root." >&2; exit 1; }

present=""
for p in $FAMILY; do dpkg -s "$p" >/dev/null 2>&1 && present="$present $p"; done
[ -n "$present" ] || { echo "vz-refresh-systemd: no systemd family packages installed."; exit 0; }

# /var/tmp (persistent CT fs), not /tmp: on a freshly-started CT /tmp may be
# remounted tmpfs during boot, which would race away a workdir created here.
workdir=$(mktemp -d /var/tmp/vz-refresh-systemd.XXXXXX)
chmod 755 "$workdir"
trap 'rm -rf "$workdir"' EXIT

echo "vz-refresh-systemd: refreshing package lists..."
apt-get update -qq

echo "vz-refresh-systemd: downloading latest noble 255.x systemd family..."
apt-mark unhold $present >/dev/null 2>&1 || true
( cd "$workdir" && apt-get download $present )

# Safety gate: every downloaded systemd*.deb MUST be 255.x or we abort without
# installing and re-hold (guards against an edited/removed pin that would
# otherwise resolve to the cgroup-v1-incapable 259).
bad=""
for f in "$workdir"/*.deb; do
	v=$(dpkg-deb -f "$f" Version)
	case "$v" in 255.*|1:255.*) ;; *) bad="$bad $(basename "$f")=$v" ;; esac
done
if [ -n "$bad" ]; then
	echo "vz-refresh-systemd: ABORT - non-255 systemd package(s) resolved (pin problem?):$bad" >&2
	apt-mark hold $present >/dev/null 2>&1 || true
	exit 1
fi

echo "vz-refresh-systemd: installing..."
dpkg -i --force-breaks --force-depends-version "$workdir"/*.deb
dpkg --configure -a --force-breaks --force-depends-version || true
apt-mark hold $present >/dev/null 2>&1 || true

ver=$(/usr/lib/systemd/systemd --version | head -1)
case "$ver" in
	*"systemd 255"*) echo "vz-refresh-systemd: OK - $ver (cgroup-v1-capable, held)." ;;
	*) echo "vz-refresh-systemd: WARNING - unexpected $ver; reboot may fail on the vz7 kernel." >&2; exit 1 ;;
esac
VZREFRESH
chmod 0755 $rootdir/usr/local/sbin/vz-refresh-systemd
echo "PSBM-163587: vz-refresh-systemd helper installed (on-demand noble systemd security refresh)."
