#!/bin/sh
# Installs a Dictate update from the .deb. Started by Dictate through pkexec
# (polkit action com.github.winidi.dictate.update, no password for the active
# local session) after the user clicked "Install update", never by itself.
#
#   pkexec /opt/dictate/dictate-update DIR
#
# DIR holds the .deb, SHA256SUMS and SHA256SUMS.sig from the update feed (see
# docs/updates.md). The helper trusts nothing the app says: it copies the
# files into a fresh root-owned directory, checks SHA256SUMS.sig against the
# public key below, the .deb against its line in SHA256SUMS and that the
# package is "dictate", and only then installs it with apt-get. Whoever can run
# it can install a Dictate package signed with our key and nothing else; apt
# refuses downgrades, so an old signed package cannot be put back either.
#
# Exit codes, each with one line on stderr:
#   1 not run through pkexec / wrong arguments   2 files missing or unreadable
#   3 signature does not match                   4 SHA256SUMS names no single valid .deb
#   5 .deb does not match its hash               6 the .deb is not the dictate package
#   7 apt-get install failed
#
# Tests only: run as a normal user (not root) with DICTATE_UPDATE_VERIFY_ONLY=1
# it does every check, with the public key from the PEM file in
# DICTATE_UPDATE_PUBKEY if set, prints "verified <deb>" and installs nothing.
# As root both variables are ignored.
set -eu
PATH=/usr/sbin:/usr/bin:/sbin:/bin
export PATH
umask 022

# Ed25519, the same key as PUBLIC_KEY in updater.py.
PUBLIC_KEY_PEM='-----BEGIN PUBLIC KEY-----
MCowBQYDK2VwAyEA7reUmbTwKWq2/Cr0a8MvX65jQ0zJjAoRZhmu9JyQm2k=
-----END PUBLIC KEY-----'

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

verify_only=0
pubkey_file=""
if [ "$(id -u)" = 0 ]; then
    if [ -z "${PKEXEC_UID:-}" ] || [ "$PKEXEC_UID" = 0 ]; then
        die 1 "run it as a normal user through pkexec"
    fi
    unset DICTATE_UPDATE_VERIFY_ONLY DICTATE_UPDATE_PUBKEY TMPDIR
elif [ "${DICTATE_UPDATE_VERIFY_ONLY:-}" = 1 ]; then
    verify_only=1
    pubkey_file=${DICTATE_UPDATE_PUBKEY:-}
else
    die 1 "run it as a normal user through pkexec"
fi

[ $# -eq 1 ] || die 1 "usage: dictate-update DIR"
for tool in openssl sha256sum dpkg-deb; do
    command -v "$tool" >/dev/null 2>&1 || die 2 "$tool is not installed"
done
src=$1
[ -d "$src" ] || die 2 "not a directory: $src"
for f in SHA256SUMS SHA256SUMS.sig; do
    [ -f "$src/$f" ] && [ -r "$src/$f" ] || die 2 "missing $f in $src"
done

# Everything below works on copies in a directory only we can write to, so
# nothing can be swapped between the checks and the install.
work=$(mktemp -d "${TMPDIR:-/tmp}/dictate-update.XXXXXX") || die 2 "cannot create a temporary directory"
trap 'rm -rf "$work"' EXIT
trap 'exit 130' HUP INT TERM
cp -- "$src/SHA256SUMS" "$work/SHA256SUMS" || die 2 "cannot copy SHA256SUMS"
cp -- "$src/SHA256SUMS.sig" "$work/SHA256SUMS.sig" || die 2 "cannot copy SHA256SUMS.sig"
if [ -z "$pubkey_file" ]; then
    pubkey_file="$work/pubkey.pem"
    printf '%s\n' "$PUBLIC_KEY_PEM" > "$pubkey_file"
fi
[ -r "$pubkey_file" ] || die 2 "cannot read the public key $pubkey_file"

openssl pkeyutl -verify -pubin -inkey "$pubkey_file" -rawin \
    -in "$work/SHA256SUMS" -sigfile "$work/SHA256SUMS.sig" >/dev/null 2>&1 \
    || die 3 "SHA256SUMS is not signed with the Dictate key"

# Exactly one .deb line ("<64 hex>  <name>" or "<64 hex> *<name>").
count=$(grep -c '\.deb$' "$work/SHA256SUMS" || true)
[ "$count" = 1 ] || die 4 "SHA256SUMS must name exactly one .deb, it names $count"
line=$(grep '\.deb$' "$work/SHA256SUMS")
want=${line%% *}
name=${line#* }
name=${name#[ *]}
printf '%s\n' "$want" | grep -Eq '^[0-9a-f]{64}$' || die 4 "SHA256SUMS has a malformed hash for the .deb"
case $name in
    */*) die 4 "refusing a file name with a path: $name" ;;
esac
printf '%s\n' "$name" | grep -Eq '^dictate_[0-9A-Za-z.+~-]+_amd64\.deb$' \
    || die 4 "refusing a file name that is not dictate_<version>_amd64.deb: $name"

[ -f "$src/$name" ] && [ -r "$src/$name" ] || die 2 "missing $name in $src"
cp -- "$src/$name" "$work/$name" || die 2 "cannot copy $name"
deb="$work/$name"
have=$(sha256sum < "$deb" | cut -d' ' -f1)
[ "$have" = "$want" ] || die 5 "$name does not match its hash in SHA256SUMS"

pkg=$(dpkg-deb -f "$deb" Package 2>/dev/null) || die 6 "$name is not a Debian package"
[ "$pkg" = dictate ] || die 6 "$name is package '$pkg', not dictate"

if [ "$verify_only" = 1 ]; then
    echo "verified $name"
    exit 0
fi

# apt reads local packages as user _apt; the files are verified and the
# directory is still root-owned, so letting others read them changes nothing.
chmod 755 "$work"
chmod 644 "$deb"
DEBIAN_FRONTEND=noninteractive apt-get install -y -q "$deb" >&2 \
    || die 7 "apt-get install of $name failed"
echo "installed $name"
