#!/bin/sh
# RemoScreen in-app update for the .deb (gdoc54, lib/self_update.dart debInstallCommand). The package installs this
# file as /opt/remoscreen/remoscreen-install-update, owned by root; RemoScreen runs it through pkexec:
#
#   pkexec /opt/remoscreen/remoscreen-install-update FILE.deb SHA256
#
# As root it copies FILE.deb into a folder only root can open, checks that the copy's SHA-256 is SHA256 (the signed
# release's) and that it is the remoscreen package, and installs that copy. What the user's own processes can write
# (the download folder) is never installed as root after it was checked: a file changed after RemoScreen verified
# it fails here (exit 65) and nothing is installed.
#
# Exit codes: 0 installed; 64 wrong arguments; 65 the file is not the signed RemoScreen package; otherwise apt-get's.
set -eu
[ "$#" -eq 2 ] || { echo "usage: $0 FILE.deb SHA256" >&2; exit 64; }
src=$1
want=$2
case "$want" in
  *[!0-9a-f]* | "") echo "remoscreen-install-update: the SHA-256 must be 64 lowercase hex digits" >&2; exit 64 ;;
esac
[ "${#want}" -eq 64 ] || { echo "remoscreen-install-update: the SHA-256 must be 64 lowercase hex digits" >&2; exit 64; }
umask 077
dir=$(mktemp -d "${TMPDIR:-/tmp}/remoscreen-update.XXXXXXXX")
trap 'rm -rf "$dir"' EXIT
cp -- "$src" "$dir/remoscreen.deb"
got=$(sha256sum "$dir/remoscreen.deb" | cut -d' ' -f1)
if [ "$got" != "$want" ]; then
  echo "remoscreen-install-update: the file does not match the signed release; nothing was installed" >&2
  exit 65
fi
if [ "$(dpkg-deb -f "$dir/remoscreen.deb" Package)" != remoscreen ]; then
  echo "remoscreen-install-update: the file is not the RemoScreen package; nothing was installed" >&2
  exit 65
fi
DEBIAN_FRONTEND=noninteractive apt-get install -y "$dir/remoscreen.deb"
