#!/bin/bash
# store-apt — what the Store runs as root: through pkexec and its own polkit action, org.rikkiti.store.apt
# ("Authentication is required to install, remove or update software"), which asks for the password every time.
# It does only these, with every argument checked:
#
#   store-apt install PKG...     apt-get install
#   store-apt remove PKG...      apt-get remove
#   store-apt upgrade PKG...     apt-get install --only-upgrade
#   store-apt full-upgrade       the whole system: apt-get update, then full-upgrade
#   store-apt update             apt-get update
#   store-apt install-deb FILE   apt-get install --reinstall --allow-downgrades /path/to/file.deb (a package opened from Files)
#
# apt's progress goes to stdout (by way of descriptor 3: see OPTS) as APT::Status-Fd lines (pmstatus/dlstatus/pmerror), which the Store reads from a
# pipe. Config files a package would change are kept as the user has them (confdef/confold), so nothing waits on a
# question; another apt running is waited for, up to a minute, rather than failing at once.
#
# A second guard beside the Store's own: nothing that would remove a Rikkiti package (rikkiti-desktop, …) runs. The
# Store shows what an install or removal takes with it before asking; this refuses even if something else asks.
#
# Everything apt and dpkg say is also kept in /var/log/rikkiti-store-apt.log (the last megabyte or so), with the time
# and what was asked. apt's own term.log has none of it: with Dpkg::Use-Pty=0 dpkg's words go only to the Store's
# pipe, so when a package's script failed (Mullvad's, 2026-11-26) the reason was nowhere afterwards.
#
# Exit: 0 done; 2 a bad argument; 3 refused (it would remove a Rikkiti package); else apt-get's own.
set -uo pipefail
export DEBIAN_FRONTEND=noninteractive LC_ALL=C.UTF-8 PATH=/usr/sbin:/usr/bin:/sbin:/bin

# The status lines go to descriptor 3, which is pointed at stdout where apt is run (3>&1), and never to 1 itself: apt
# closes its status descriptor in dpkg, so with Status-Fd=1 every package script ran with no stdout. One that prints
# under `set -e` (Mullvad's "Running before-remove.sh", 2026-11-26) failed at its first echo, "write error: Bad file
# descriptor", and dpkg left the package half done: no VPN and no network until it was put in again from a terminal.
OPTS=(-y -o APT::Status-Fd=3 -o Dpkg::Use-Pty=0 -o DPkg::Lock::Timeout=60
	-o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold)

bad() { echo "store-apt: $*" >&2; exit 2; }
valid_pkg() { [[ "$1" =~ ^[a-z0-9][a-z0-9+.-]+(:[a-z0-9-]+)?$ ]]; }

# guard: what apt would remove (simulated, as the real run would do it) must not include a Rikkiti package.
guard() {
	local out
	out="$(apt-get -s -o Debug::NoLocking=1 "$@" 2>/dev/null)" || return 0 # apt's own error comes from the real run
	if grep -qE '^Remv rikkiti' <<<"$out"; then
		echo "store-apt: refused: this would remove $(grep -E '^Remv rikkiti' <<<"$out" | awk '{print $2}' | paste -sd, -)" >&2
		exit 3
	fi
}

# keep_log: from here on, what this and apt write goes to the log as well as to the Store. Never a reason to fail.
LOG=/var/log/rikkiti-store-apt.log
keep_log() {
	[ -w /var/log ] || return 0
	if [ -f "$LOG" ] && [ "$(stat -c %s "$LOG" 2>/dev/null || echo 0)" -gt 1000000 ]; then mv -f "$LOG" "$LOG.1" 2>/dev/null || true; fi
	( umask 022; printf '\n==== %s  store-apt %s\n' "$(date '+%F %T')" "$*" >>"$LOG" ) 2>/dev/null || return 0
	exec > >(tee -a "$LOG") 2>&1
}

verb="${1:-}"
[ $# -gt 0 ] && shift
[ -n "$verb" ] && keep_log "$verb" "$@"
case "$verb" in
install | remove | upgrade)
	[ $# -ge 1 ] || bad "which packages?"
	for p in "$@"; do valid_pkg "$p" || bad "not a package name: $p"; done
	case "$verb" in
	install) guard install "$@"; exec apt-get "${OPTS[@]}" install "$@" 3>&1 ;;
	remove) guard remove "$@"; exec apt-get "${OPTS[@]}" remove "$@" 3>&1 ;;
	upgrade) guard install --only-upgrade "$@"; exec apt-get "${OPTS[@]}" install --only-upgrade "$@" 3>&1 ;;
	esac
	;;
full-upgrade)
	[ $# -eq 0 ] || bad "full-upgrade takes nothing"
	apt-get -o APT::Status-Fd=3 -o DPkg::Lock::Timeout=60 update 3>&1 || true # a mirror down still upgrades from the others
	guard full-upgrade
	exec apt-get "${OPTS[@]}" full-upgrade 3>&1
	;;
update)
	[ $# -eq 0 ] || bad "update takes nothing"
	exec apt-get -o APT::Status-Fd=3 -o DPkg::Lock::Timeout=60 update 3>&1
	;;
install-deb)
	[ $# -eq 1 ] || bad "one file"
	f="$1"
	[[ "$f" == /* && "$f" == *.deb ]] || bad "not a .deb file by its full path: $f"
	[ -f "$f" ] && [ ! -L "$f" ] || bad "no such file: $f"
	# The file's version goes in, whatever is installed now: the same again (--reinstall) or an older one
	# (--allow-downgrades). The Store's page says which before Install is pressed. Without them apt answered "already
	# the newest version" and did nothing, and the Store said it was installed.
	guard install --reinstall --allow-downgrades "$f"
	exec apt-get "${OPTS[@]}" install --reinstall --allow-downgrades "$f" 3>&1
	;;
*)
	bad "install, remove, upgrade PKG...; full-upgrade; update; install-deb FILE"
	;;
esac
