#!/bin/bash

if [ -z "$1" ]; then
    exit 1
fi

hash_ok=0
case "$2" in
    *[!0-9a-f]*) ;;
    ????????????????????????????????????????????????????????????????) hash_ok=1 ;;
esac
if [ "$hash_ok" != 1 ]; then
    echo "Invalid or missing sha256 hash" >&2
    exit 1
fi

platform=$(cat /etc/windscribe/platform 2>/dev/null || true)
if [ -z "$platform" ]; then
    # should not be here
    platform="linux_deb_x64_cli"
fi

PRIVILEGED_SCRIPT='
set -eu
SRC=$1
HASH=$2
PLATFORM=$3
WS_DBUS=$4
WS_XDG=$5

case "$PLATFORM" in
    linux_deb_x64_cli|linux_deb_arm64_cli) EXT=deb ;;
    linux_rpm_x64_cli|linux_rpm_arm64_cli|linux_rpm_opensuse_x64_cli) EXT=rpm ;;
    linux_zst_x64_cli) EXT=pkg.tar.zst ;;
    *) echo "Unsupported platform $PLATFORM" >&2; exit 1 ;;
esac

STAGING=/var/lib/windscribe/updates
install -d -m 700 -o root -g root "$STAGING"
STAGED="$STAGING/update.$EXT"

install -m 600 -o root -g root -- "$SRC" "$STAGED"
cleanup() { rm -f -- "$STAGED"; }
trap cleanup EXIT

ACTUAL=$(sha256sum -- "$STAGED" | cut -d" " -f1)
if [ "$ACTUAL" != "$HASH" ]; then
    echo "Hash mismatch, aborting install" >&2
    exit 2
fi

USER_NAME=$(getent passwd "$SUDO_UID" | cut -d: -f1)
: "${WS_XDG:=/run/user/$SUDO_UID}"

trap - EXIT
(
    trap cleanup EXIT

    pkill -TERM -x Windscribe 2>/dev/null || true
    i=0
    while pgrep -x Windscribe >/dev/null && [ $i -lt 100 ]; do
        sleep 0.1
        i=$((i+1))
    done
    pkill -KILL -x Windscribe 2>/dev/null || true

    case "$PLATFORM" in
        linux_deb_x64_cli|linux_deb_arm64_cli)
            APT_LISTBUGS_FRONTEND=none apt install -y --reinstall "$STAGED"
            ;;
        linux_rpm_x64_cli|linux_rpm_arm64_cli)
            if command -v rpm-ostree >/dev/null; then
                rpm-ostree upgrade --cache-only --reboot --uninstall windscribe --install "$STAGED"
            else
                dnf upgrade --cacheonly -y "$STAGED"
            fi
            ;;
        linux_rpm_opensuse_x64_cli)
            if [ -f /usr/sbin/transactional-update ]; then
                transactional-update -n pkg install --allow-unsigned-rpm "$STAGED"
                reboot
                exit 0
            else
                zypper --non-interactive install --force --allow-unsigned-rpm "$STAGED"
            fi
            ;;
        linux_zst_x64_cli)
            pacman -U --noconfirm "$STAGED"
            ;;
    esac

    runuser -u "$USER_NAME" -- env \
        DBUS_SESSION_BUS_ADDRESS="$WS_DBUS" \
        XDG_RUNTIME_DIR="$WS_XDG" \
        systemctl --user restart windscribe
) </dev/null >/dev/null 2>&1 &

exit 0
'

sudo -k sh -c "$PRIVILEGED_SCRIPT" _ "$1" "$2" "$platform" \
    "${DBUS_SESSION_BUS_ADDRESS:-}" "${XDG_RUNTIME_DIR:-}"
rc=$?
case $rc in
    126|127) exit 3 ;;
    *) exit $rc ;;
esac
