#!/bin/sh
set -eu
PATH=/usr/sbin:/usr/bin:/sbin:/bin
export PATH
umask 077

case "$(uname -s)" in
    Darwin)
        home='/Library/Application Support/Nilo Appliance'
        state=/var/db/nilo-appliance
        work=/var/db/nilo-appliance-updates
        account=_niloappliance
        ;;
    Linux)
        home=/usr/lib/nilo-appliance
        state=/var/lib/nilo-appliance
        work=/var/lib/nilo-appliance-updates
        account=nilo-appliance
        ;;
    *) exit 1 ;;
esac
key="$home/update-signing-key.pem"
if [ ! -f "$key" ] || [ ! -f "$state/take-release" ]; then exit 0; fi
mkdir -p "$work"
chmod 0755 "$work"
# Read the daemon's request with its own privileges. The root-owned work directory
# contains only files created by this helper and survives replacement of the package.
if [ "$account" = _niloappliance ]; then
    request="$(sudo -n -u "$account" /bin/dd if="$state/take-release" bs=512 count=1 2>/dev/null)"
else
    request="$(runuser -u "$account" -- /bin/dd if="$state/take-release" bs=512 count=1 2>/dev/null)"
fi
if ! printf '%s\n' "$request" | LC_ALL=C grep -Exq '[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12} [1-9][0-9]{0,17} [a-f0-9]{40} [a-f0-9]{64} [1-9][0-9]{0,11}'; then exit 0; fi
# Field formats are checked before interpreting them or building a URL.
IFS=' ' read -r attempt release revision digest expires <<REQUEST
$request
REQUEST
# A multi-line file is invalid even when one line looked like a command.
if [ "$request" != "$attempt $release $revision $digest $expires" ]; then exit 0; fi
read -r installed package < "$home/update-installation"
if [ "$release" -le "$installed" ] || [ "$expires" -le "$(date +%s)" ]; then exit 0; fi
case "$(uname -s):$(uname -m):$package" in
    Darwin:arm64:nilo-appliance-macos-arm64.pkg | \
    Linux:x86_64:nilo-appliance-linux-amd64.deb | Linux:aarch64:nilo-appliance-linux-arm64.deb | \
    Linux:x86_64:nilo-appliance-linux-x86_64.rpm | Linux:aarch64:nilo-appliance-linux-aarch64.rpm) ;;
    *) exit 1 ;;
esac
if [ -f "$work/receipt" ]; then
    read -r previous status < "$work/receipt"
    if [ "$previous" = "$attempt" ]; then exit 0; fi
fi
stage="$(mktemp -d "$work/package.XXXXXX")"
receipt() {
    printf '%s %s\n' "$attempt" "$1" > "$stage/receipt"
    chmod 0644 "$stage/receipt"
    mv -f "$stage/receipt" "$work/receipt"
}
cleanup() {
    result=$?
    trap - EXIT
    if [ "$result" -ne 0 ]; then receipt failed; fi
    rm -rf "$stage"
    exit "$result"
}
trap cleanup EXIT
receipt started
origin="https://downloads.nilo-assistant.com/nilo-appliance-releases/$release-$revision/$digest"
printf '%s %s %s %s\n' "$release" "$revision" "$digest" "$package" > "$stage/release"
curl -q --fail --silent --show-error --proto '=https' --connect-timeout 10 --max-time 20 \
    --max-filesize 16384 --output "$stage/release.sig" "$origin/$package.sig"
openssl dgst -sha256 -verify "$key" -signature "$stage/release.sig" "$stage/release"
curl -q --fail --silent --show-error --proto '=https' --connect-timeout 10 --max-time 900 \
    --max-filesize 671088640 --output "$stage/$package" "$origin/$package"
actual="$(openssl dgst -sha256 -r "$stage/$package" | cut -d ' ' -f 1)"
test "$actual" = "$digest"

case "$package" in
    *.deb)
        apt-get -o APT::Update::Error-Mode=any update
        DEBIAN_FRONTEND=noninteractive apt-get -y --no-install-recommends --no-remove \
            -o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold install "$stage/$package"
        ;;
    *.rpm) dnf --refresh --setopt=install_weak_deps=False -y install "$stage/$package" ;;
    *.pkg) /usr/sbin/installer -pkg "$stage/$package" -target / ;;
esac
