#!/bin/sh
# Installs the updates waiting for the phi packages on this machine.
#
# The list of packages is computed here rather than passed in. That is the whole
# security argument for this being a unit: no argument crosses the privilege
# boundary, so there is nothing to validate and nothing to smuggle through. A
# caller can ask for this to run; it cannot ask for it to run on something else.
#
# Only the phi packages. Everything else on the machine is Debian's, and
# unattended-upgrades is what applies those - reviewed, shipped, and configured
# with a window. Sweeping the operating system into a button somebody presses
# from a browser would restart things nobody asked about.
set -eu

# apt speaks the machine's language; its output lands in the journal and in the
# settings dialog, which are English. The unit runs with no locale of its own,
# so say it here rather than trust the environment.
export LC_ALL=C.UTF-8 LANGUAGE=C

# Refresh first, or the button would install whatever was known the last time
# something else happened to look.
apt-get update

# Installed, not merely known: dpkg lists packages that were removed but whose
# configuration is still there, and asking apt to upgrade one of those would
# install it.
packages=$(dpkg-query -W -f='${Package} ${Status}\n' 'phi-*' 2>/dev/null \
    | awk '$4 == "installed" { print $1 }')

if [ -z "$packages" ]; then
    echo "phi-update: no phi packages are installed."
    exit 0
fi

echo "phi-update: $(echo "$packages" | tr '\n' ' ')"

# --only-upgrade so that a name which is no longer a package cannot become an
# installation. --with-new-pkgs so an upgrade that needs a dependency it did not
# need before can bring it: refusing there would hold the update back silently.
# The conffile options are unattended-upgrades' own: keep what the administrator
# edited, take the maintainer's version of everything else.
DEBIAN_FRONTEND=noninteractive \
exec apt-get -y \
    --with-new-pkgs \
    --only-upgrade \
    -o Dpkg::Options::=--force-confdef \
    -o Dpkg::Options::=--force-confold \
    install $packages
