#!/bin/sh

# (C) 2017-2025 by Christian Hesse <mail@eworm.de>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

set -e

# verify this is for us or exit gracefully
if [ "$(readlink '/system-update')" != '/var/cache/pacman/pkg' ]; then
	exit 0
fi

# exclude /etc/pacman.d/offline.conf
function finish { rm -f /run/pacman.conf; }
trap finish EXIT
sed \
	-e '/^Include *= *\/etc\/pacman\.d\/offline\.conf$/s|^|#|' \
	-e '/^#Include *= *\/etc\/pacman\.d\/offline-include\.conf$/s|^#||' \
	< /etc/pacman.conf > /run/pacman.conf

# remove triggering symlink and reboot & poweroff override
rm --force \
	/system-update \
	/run/systemd/system/systemd-poweroff.service \
	/run/systemd/system/systemd-reboot.service

# install updates
if [ "$(pacman --sync --print --needed archlinux-keyring | wc -l)" -gt 0 ]; then
	pacman --sync --noconfirm archlinux-keyring
fi
pacman --config /run/pacman.conf --sync --noconfirm --sysupgrade

# clean up config file, drop trap
rm -f /run/pacman.conf
trap - EXIT

# clean up package cache
pacman --sync --noconfirm --clean

# poweroff or (soft-)reboot
if [ -e '/run/system-update-poweroff' ]; then
	exec systemctl poweroff
elif [ -s "/usr/lib/modules/$(uname -r)/pkgbase" ]; then
	exec systemctl soft-reboot
else
	exec systemctl reboot
fi
