#!/bin/sh
# SPDX-FileCopyrightText: Copyright (C) 2026 Shenzhen Wuji Technology Co., Ltd.
# SPDX-License-Identifier: MPL-2.0
#
# Privileged install helper for Wuji Studio self-update (m-7036341637).
#
# Invoked through pkexec (polkit action tech.wuji.studio.update). This is the
# only code path the updater runs as root, so it narrows what root will do:
# the target must be a real file inside a Studio-managed updates directory,
# named like our package, and its control field must identify the wuji-studio
# package. Everything else is refused.
set -eu

err() {
  echo "wuji-studio-update-helper: $*" >&2
}

deb_path="${1:-}"
if [ -z "$deb_path" ]; then
  err "usage: wuji-studio-update-helper <path-to-wuji-studio.deb>"
  exit 2
fi

canonical="$(readlink -f -- "$deb_path")" || {
  err "cannot resolve $deb_path"
  exit 2
}

if [ ! -f "$canonical" ]; then
  err "refusing $canonical: not a regular file"
  exit 2
fi

case "$canonical" in
  */.wuji/studio/updates/*) ;;
  *)
    err "refusing $canonical: not inside a Studio-managed updates directory"
    exit 2
    ;;
esac

base="$(basename -- "$canonical")"
case "$base" in
  wuji-studio_*.deb) ;;
  *)
    err "refusing $base: not a wuji-studio package file"
    exit 2
    ;;
esac

pkg="$(dpkg-deb --field "$canonical" Package)" || {
  err "refusing $canonical: unreadable package metadata"
  exit 2
}
if [ "$pkg" != "wuji-studio" ]; then
  err "refusing package '$pkg': only wuji-studio may be installed"
  exit 2
fi

# Delegate the actual verify + install to the Studio binary's compiled
# subcommand. It verifies the minisign signature over SHA256SUMS and the deb's
# own sha256 against an embedded trusted key before invoking apt — the shell
# checks above are only a coarse first gate. The subcommand forwards apt's
# machine-readable progress on stdout; its exit status is ours.
exec /usr/bin/wuji-studio __update_install "$canonical"
