#!/bin/sh
set -eu

DIR=/opt/ather-admin/updates
REQUEST="$DIR/admin-update-request"
MANIFEST="$DIR/manifest-admin.json"
LOG="$DIR/admin-install.log"
PUBLIC_KEY_DER_B64="MCowBQYDK2VwAyEAOI0o3QRFD5tztdbKWVCHBj3vWKPCtliTdFOdxZBQBU4="

exec >"$LOG" 2>&1
echo "Ather Admin update started at $(date)"

PKG=$(head -n 1 "$REQUEST")
case "$PKG" in
    "$DIR"/packages/ather-admin-*.deb|"$DIR"/packages/ather-admin-*.rpm) ;;
    *) echo "Refusing to install $PKG: it is not a staged Ather Admin package"; exit 1 ;;
esac
case "$PKG" in
    *..*) echo "Refusing to install $PKG"; exit 1 ;;
esac
[ -f "$PKG" ] || { echo "$PKG does not exist"; exit 1; }

WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT
{
    echo "-----BEGIN PUBLIC KEY-----"
    echo "$PUBLIC_KEY_DER_B64"
    echo "-----END PUBLIC KEY-----"
} > "$WORK/release.pem"
base64 -d "$MANIFEST.sig" > "$WORK/manifest.sig"
cp "$MANIFEST" "$WORK/manifest.json"
cp "$PKG" "$WORK/package"

openssl pkeyutl -verify -pubin -inkey "$WORK/release.pem" -rawin -in "$WORK/manifest.json" -sigfile "$WORK/manifest.sig"
grep -q '"product": "admin"' "$WORK/manifest.json" || { echo "The manifest is not an Admin manifest"; exit 1; }
SUM=$(sha256sum "$WORK/package" | cut -d ' ' -f 1)
grep -q "\"sha256\": \"$SUM\"" "$WORK/manifest.json" || { echo "The package is not listed in the signed Admin manifest"; exit 1; }
echo "Verified $PKG ($SUM) against the signed manifest"

status=0
case "$PKG" in
    *.deb)
        mv "$WORK/package" "$WORK/package.deb"
        if command -v apt-get >/dev/null 2>&1; then
            DEBIAN_FRONTEND=noninteractive apt-get install -y --allow-downgrades "$WORK/package.deb" || status=$?
        else
            dpkg -i "$WORK/package.deb" || status=$?
        fi
        ;;
    *.rpm)
        mv "$WORK/package" "$WORK/package.rpm"
        if command -v dnf >/dev/null 2>&1; then
            dnf install -y "$WORK/package.rpm" || status=$?
        elif command -v yum >/dev/null 2>&1; then
            yum install -y "$WORK/package.rpm" || status=$?
        else
            rpm -U --oldpackage "$WORK/package.rpm" || status=$?
        fi
        ;;
esac
echo "Install finished with status $status"
rm -f "$REQUEST"
systemctl daemon-reload || true
systemctl restart ather-admin.service
exit $status
