#!/bin/bash

# Runs "apt upgrade" from a specified repository path, which must be mounted
# locally. This script is intended to be run as a transient-scope systemd
# service unit, i.e. systemd-run, or in a comparable environment.

# Make sure the directory exists.
if [[ ! -d "$1" ]]; then
    echo "${0##*/} <repo-path>"
    exit 0
fi

TMP=$(mktemp --suffix=".sources")
trap "rm -f $TMP" EXIT

# Write our own sources.list entry (deb822 format), to keep apt from accessing
# anything OTHER than the indicated repository. Specifically, this prevents us
# from using anything that might appear in the local system's
# /etc/apt/sources.list[.d].
cat > $TMP <<EOF
Types: deb
URIs: file:$1
Suites: unstable
Components: main
Allow-Insecure: yes
Trusted: yes
Check-Valid-Until: no
Check-Date: no
EOF

ARGS="--option Dir::Etc::SourceList=$TMP --option Dir::Etc::SourceParts=/dev/null"

# Run the update, allowing the installation of new packages from the repository
# if necessary. We don't blindly install ALL of the packages in the repository,
# only the ones that somehow relate to packages already installed. This logic
# helps prevent us accepting an unsigned package in systems that are already
# configured to use signed packages. (Note: not tested extensively.)
#
# If the administrator wants to drag in a new package, they must add it as a
# dependency to an existing package, i.e. device-<devicename>.
#
apt update $ARGS && apt upgrade --assume-yes --with-new-pkgs $ARGS
