#!/bin/sh
# Upgrades the netwarden package from the Netwarden repository, when the agent
# has asked for it by creating /var/lib/netwarden/update-request.
#
# Run as root by netwarden-update.service, outside the agent's sandbox: the
# agent's own unit (ProtectSystem=strict) cannot write /usr/bin/netwarden. The
# request only says "check now". What gets installed is whatever the signed
# repository holds, verified by apt or dnf against the key the package
# installed, and only the netwarden package is touched. The package's postinst
# restarts the agent.
#
# To stop agents upgrading themselves, set self_update: false in
# /etc/netwarden/netwarden.conf; the agent then never makes a request.
set -eu

request=/var/lib/netwarden/update-request

[ -e "$request" ] || exit 0
# Consumed before the upgrade runs, so a failing upgrade is not retried in a
# loop by the path unit; the agent asks again a day later.
rm -f "$request"

if [ -f /etc/apt/sources.list.d/netwarden.list ] && command -v apt-get >/dev/null 2>&1; then
    export DEBIAN_FRONTEND=noninteractive
    apt-get -q -o DPkg::Lock::Timeout=600 \
        -o Dir::Etc::sourcelist=sources.list.d/netwarden.list \
        -o Dir::Etc::sourceparts=- -o APT::Get::List-Cleanup=0 \
        update
    apt-get -q -y -o DPkg::Lock::Timeout=600 \
        -o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold \
        install --only-upgrade netwarden
elif [ -f /etc/yum.repos.d/netwarden.repo ] && command -v dnf >/dev/null 2>&1; then
    dnf -q -y --refresh --disablerepo='*' --enablerepo=netwarden upgrade netwarden
elif [ -f /etc/yum.repos.d/netwarden.repo ] && command -v yum >/dev/null 2>&1; then
    yum -q -y --disablerepo='*' --enablerepo=netwarden update netwarden
else
    echo "netwarden-update: no Netwarden apt or yum repository is configured" >&2
    exit 1
fi
