#!/bin/sh
set -eu
HELPER="/usr/local/libexec/pyacket-root-launcher"

if [ ! -x "$HELPER" ]; then
    echo "pyacket elevated launcher가 설치되어 있지 않습니다: $HELPER" >&2
    echo "배포 패키지에서 sudo ./linux/install-linux.sh 를 다시 실행하세요." >&2
    exit 69
fi

if [ "$(id -u)" -eq 0 ]; then
    exec "$HELPER" --uid "${SUDO_UID:-0}" --display "${DISPLAY:-}" \
        --wayland-display "${WAYLAND_DISPLAY:-}" --xauthority "${XAUTHORITY:-}" \
        --session-type "${XDG_SESSION_TYPE:-}" -- "$@"
fi

uid="$(id -u)"
# 터미널 실행은 sudo를 우선 사용해 오류/진단 출력을 그대로 보여준다.
if [ -t 0 ] && command -v sudo >/dev/null 2>&1; then
    exec sudo \
        "$HELPER" --uid "$uid" --display "${DISPLAY:-}" \
        --wayland-display "${WAYLAND_DISPLAY:-}" --xauthority "${XAUTHORITY:-}" \
        --session-type "${XDG_SESSION_TYPE:-}" -- "$@"
fi
if command -v pkexec >/dev/null 2>&1; then
    exec pkexec "$HELPER" --uid "$uid" --display "${DISPLAY:-}" \
        --wayland-display "${WAYLAND_DISPLAY:-}" --xauthority "${XAUTHORITY:-}" \
        --session-type "${XDG_SESSION_TYPE:-}" -- "$@"
fi

echo "sudo 또는 pkexec(polkit)가 없어 pyacket을 root로 실행할 수 없습니다." >&2
exit 77
