#!/bin/bash
# R-VPN Lite 0.3.9: installs an update the app has downloaded and checked against the manifest. The app runs it
# through pkexec (polkit action app.rvpn.plus.update), so this runs as root and trusts the file only as far as
# it checks it here: a copy out of the user's reach, an R-VPN Lite package of this installation's format.
#   rvpn-update FILE      exit 0 — installed; 2–5 — refused or failed (nothing changed by this script)
set -euo pipefail
export PATH=/usr/sbin:/usr/bin:/sbin:/bin LC_ALL=C DEBIAN_FRONTEND=noninteractive
[[ $# -eq 1 ]] || exit 2
src=$1
[[ -f $src && ! -L $src ]] || exit 3
format=deb
[[ $(cat /usr/lib/rvpn-plus/package-format 2>/dev/null || true) == rpm ]] && format=rpm
work=$(mktemp -d /var/tmp/rvpn-update.XXXXXX)
trap 'rm -rf -- "$work"' EXIT
# apt reads local packages as its own user: let it in, root still owns everything
chmod 0755 "$work"
pkg=$work/update.$format
install -m 0644 -- "$src" "$pkg"
if [[ $format == rpm ]]; then
    name=$(rpm -qp --qf '%{NAME}' "$pkg" 2>/dev/null) || exit 4
    [[ $name == rvpn-plus ]] || exit 4
    dnf -y install "$pkg" || exit 5
else
    name=$(dpkg-deb -f "$pkg" Package 2>/dev/null) || exit 4
    [[ $name == rvpn-plus ]] || exit 4
    apt-get install -y --no-install-recommends "$pkg" || exit 5
fi
