#!/bin/sh
# farview-update-helper <version> <package> <SHA256SUMS> <SHA256SUMS.asc>
#
# Installs a Farview update that the app has already downloaded, as root, through
# pkexec (polkit action ai.synapsi.farview.update, which names this file by path).
#
# EVERY ARGUMENT IS HOSTILE. The caller is a user's process, and what it passes is
# whatever it likes. So:
#   - the version has to be YYYY.M.N and nothing else;
#   - each file has to be a regular file, not a symlink, owned by the user who ran
#     pkexec ($PKEXEC_UID) and of a sane size -- otherwise a user could make root
#     read /etc/shadow into something they can see, or feed it a file to swap;
#   - the CONTENT of each is copied into a fresh directory only root can enter, and
#     everything after that is done on the copies, never on the paths given;
#   - the signature on SHA256SUMS has to be valid, made by the release key (primary
#     fingerprint pinned below, against the keyring that ships next to this file),
#     and the package's digest has to be the one SHA256SUMS lists for exactly the
#     name this version's package has;
#   - the version has to be newer than the one installed: this is not a way to
#     downgrade.
# Only then does it call the package manager. File contents are never printed.
#
# Exit codes: 0 done; 64 usage; 65 bad version; 66 bad input file; 67 a tool or the
# keyring is missing; 68 bad signature; 69 digest mismatch or file not listed;
# 70 not newer than what is installed; 71 the package manager failed; 72 not run
# through pkexec.
#
# FARVIEW_HELPER_DRY_RUN=1 skips only the final install command (and the
# must-be-root check), for tests. pkexec drops the environment, so it cannot be set
# by a user to change what the real thing does.

umask 077
PATH=/usr/sbin:/usr/bin:/sbin:/bin
export PATH
LC_ALL=C
export LC_ALL

PRIMARY=004432F6A65FC16622822243DDF673DB4582AD8F
SUBKEY=5A6F2C906B8C1AC8F894748EEB966D868DF807AE
PACKAGE_NAME=farview-desktop
MAX_SUMS=65536
MAX_SIG=16384
MAX_PKG=536870912

# The keyring by absolute path, never next to $0: $0 is whatever path the caller
# exec'd, and a symlink to this script elsewhere would bring its own keyring along.
# Only the dry run (tests, from the source tree; pkexec drops the variable) reads it
# from beside the script.
KEYRING=/opt/Farview/resources/synapsi-releases.gpg
[ -n "$FARVIEW_HELPER_DRY_RUN" ] && KEYRING=${0%/*}/synapsi-releases.gpg

die() {
  code=$1
  shift
  echo "farview-update-helper: $*" >&2
  exit "$code"
}

[ "$#" -eq 4 ] || die 64 "usage: farview-update-helper <version> <package> <SHA256SUMS> <SHA256SUMS.asc>"
version=$1
pkg=$2
sums=$3
sig=$4

if [ -z "$FARVIEW_HELPER_DRY_RUN" ] && [ "$(id -u)" != 0 ]; then
  die 72 "must run as root, through pkexec"
fi
case $PKEXEC_UID in
  '' | *[!0-9]*) die 72 "PKEXEC_UID is not set: run through pkexec" ;;
esac

# --- the version -------------------------------------------------------------
case $version in
  '' | *[!0-9.]*) die 65 "not a version" ;;
esac
printf '%s\n' "$version" | grep -Eq '^[0-9]{4}\.[0-9]{1,2}\.[0-9]{1,3}$' || die 65 "not a version"

# --- which package is this ---------------------------------------------------
# The two files of THIS machine's architecture, and no others: a package of the other one
# is refused here rather than left to apt or dnf to refuse (or, for rpm -U, not to).
case $(uname -m 2>/dev/null) in
  x86_64) deb_arch=amd64 rpm_arch=x86_64 ;;
  aarch64 | arm64) deb_arch=arm64 rpm_arch=aarch64 ;;
  *) die 67 "there is no Farview package for this machine's architecture" ;;
esac
deb=farview_${version}_${deb_arch}.deb
rpm=farview-${version}.${rpm_arch}.rpm
base=${pkg##*/}
if [ "$base" = "$deb" ]; then
  kind=deb
elif [ "$base" = "$rpm" ]; then
  kind=rpm
else
  die 66 "the package is not named $deb or $rpm"
fi

# --- the inputs --------------------------------------------------------------
check_input() {
  [ -f "$1" ] && [ ! -L "$1" ] || die 66 "$2 is not a regular file"
  owner=$(stat -c %u -- "$1" 2>/dev/null) || die 66 "cannot look at $2"
  [ "$owner" = "$PKEXEC_UID" ] || die 66 "$2 is not yours"
  size=$(stat -c %s -- "$1" 2>/dev/null) || die 66 "cannot look at $2"
  [ "$size" -gt 0 ] && [ "$size" -le "$3" ] || die 66 "$2 has an unreasonable size"
}
check_input "$pkg" "the package" "$MAX_PKG"
check_input "$sums" "SHA256SUMS" "$MAX_SUMS"
check_input "$sig" "SHA256SUMS.asc" "$MAX_SIG"

for tool in gpgv sha256sum awk stat dd mktemp; do
  command -v "$tool" >/dev/null 2>&1 || die 67 "$tool is not installed"
done
[ -f "$KEYRING" ] || die 67 "the release keyring is missing"

T=$(mktemp -d /var/tmp/farview-update.XXXXXX 2>/dev/null || mktemp -d) || die 67 "no temporary directory"
trap 'rm -rf "$T"' EXIT
trap 'exit 130' HUP INT TERM
mkdir "$T/gnupg" || die 67 "no temporary directory"

copy() {
  dd if="$1" of="$2" bs=65536 iflag=nofollow status=none 2>/dev/null || die 66 "cannot read $3"
}
copy "$sums" "$T/SHA256SUMS" "SHA256SUMS"
copy "$sig" "$T/SHA256SUMS.asc" "SHA256SUMS.asc"
copy "$pkg" "$T/$base" "the package"

# --- the signature -----------------------------------------------------------
status=$(gpgv --homedir "$T/gnupg" --keyring "$KEYRING" --status-fd 1 "$T/SHA256SUMS.asc" "$T/SHA256SUMS" 2>/dev/null) ||
  die 68 "SHA256SUMS is not validly signed"
case $status in
  *EXPKEYSIG* | *REVKEYSIG* | *EXPSIG* | *BADSIG* | *ERRSIG*) die 68 "SHA256SUMS is not validly signed" ;;
esac
good=$(printf '%s\n' "$status" | awk -v p="$PRIMARY" -v s="$SUBKEY" '
  $1 == "[GNUPG:]" && $2 == "VALIDSIG" && $NF == p && ($3 == p || $3 == s) { n++ }
  END { print n + 0 }')
[ "$good" -ge 1 ] || die 68 "SHA256SUMS is not signed by the Farview release key"

# --- the digest --------------------------------------------------------------
listed=$(awk -v n="$base" 'length($0) > 66 && substr($0, 65, 2) == "  " && substr($0, 67) == n { print substr($0, 1, 64) }' "$T/SHA256SUMS")
case $listed in
  '') die 69 "$base is not in SHA256SUMS" ;;
  *'
'*) die 69 "$base is in SHA256SUMS twice" ;;
  *[!0-9a-f]*) die 69 "SHA256SUMS is malformed" ;;
esac
[ "${#listed}" -eq 64 ] || die 69 "SHA256SUMS is malformed"
actual=$(sha256sum -- "$T/$base" | awk '{ print $1 }')
[ "$actual" = "$listed" ] || die 69 "the package does not match SHA256SUMS"

# --- newer than what is installed --------------------------------------------
if [ "$kind" = deb ]; then
  command -v dpkg-query >/dev/null 2>&1 || die 67 "dpkg-query is not installed"
  installed=$(dpkg-query -W -f='${Version}' "$PACKAGE_NAME" 2>/dev/null) || die 70 "$PACKAGE_NAME is not installed"
  if command -v dpkg >/dev/null 2>&1; then
    dpkg --compare-versions "$installed" lt "$version" || die 70 "$version is not newer than $installed"
  else
    older=$(printf '%s\n%s\n' "$installed" "$version" | sort -V | head -n 1)
    [ "$older" = "$installed" ] && [ "$installed" != "$version" ] || die 70 "$version is not newer than $installed"
  fi
else
  command -v rpm >/dev/null 2>&1 || die 67 "rpm is not installed"
  installed=$(rpm -q --qf '%{VERSION}' "$PACKAGE_NAME" 2>/dev/null) || die 70 "$PACKAGE_NAME is not installed"
  older=$(printf '%s\n%s\n' "$installed" "$version" | sort -V | head -n 1)
  [ "$older" = "$installed" ] && [ "$installed" != "$version" ] || die 70 "$version is not newer than $installed"
fi

# --- install -----------------------------------------------------------------
if [ -n "$FARVIEW_HELPER_DRY_RUN" ]; then
  echo "farview-update-helper: verified $base ($installed -> $version), dry run"
  exit 0
fi

if [ "$kind" = deb ]; then
  DEBIAN_FRONTEND=noninteractive apt-get install -y -o APT::Sandbox::User=root -- "$T/$base" >/dev/null 2>&1 ||
    die 71 "apt-get could not install $version"
elif command -v dnf >/dev/null 2>&1; then
  dnf -y install "$T/$base" >/dev/null 2>&1 || die 71 "dnf could not install $version"
elif command -v zypper >/dev/null 2>&1; then
  zypper --non-interactive --no-gpg-checks install "$T/$base" >/dev/null 2>&1 || die 71 "zypper could not install $version"
else
  rpm -U --nosignature "$T/$base" >/dev/null 2>&1 || die 71 "rpm could not install $version"
fi
echo "farview-update-helper: installed $version"
exit 0
