#!/bin/sh
set -eu

HELPER="/usr/local/libexec/pyacket-root-launcher"
CLI_LAUNCHER="/usr/local/bin/pyacket"

notify() {
    if command -v notify-send >/dev/null 2>&1; then
        notify-send "pyacket" "$1" >/dev/null 2>&1 || true
    fi
}

launch_terminal_sudo() {
    notify "polkit/pkexec를 사용할 수 없어 터미널 sudo 인증으로 전환합니다."

    # Debian/Kali의 x-terminal-emulator alternative는 -e 뒤의 command와
    # argument를 그대로 전달한다. Kali Xfce를 포함해 이 경로를 우선 사용한다.
    if command -v x-terminal-emulator >/dev/null 2>&1; then
        exec x-terminal-emulator -T "pyacket 관리자 인증" -e "$CLI_LAUNCHER" "$@"
    fi
    if command -v xfce4-terminal >/dev/null 2>&1; then
        exec xfce4-terminal --title="pyacket 관리자 인증" --execute "$CLI_LAUNCHER" "$@"
    fi
    if command -v gnome-terminal >/dev/null 2>&1; then
        exec gnome-terminal --title="pyacket 관리자 인증" -- "$CLI_LAUNCHER" "$@"
    fi
    if command -v konsole >/dev/null 2>&1; then
        exec konsole -p tabtitle="pyacket 관리자 인증" -e "$CLI_LAUNCHER" "$@"
    fi
    if command -v xterm >/dev/null 2>&1; then
        exec xterm -T "pyacket 관리자 인증" -e "$CLI_LAUNCHER" "$@"
    fi

    notify "pkexec와 GUI terminal을 찾지 못했습니다. 터미널에서 pyacket을 실행하세요."
    echo "pkexec와 GUI terminal을 찾지 못했습니다. 터미널에서 pyacket을 실행하세요." >&2
    exit 77
}

if [ ! -x "$HELPER" ]; then
    notify "설치된 elevated launcher를 찾지 못했습니다. installer를 다시 실행하세요."
    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

if command -v pkexec >/dev/null 2>&1; then
    exec pkexec "$HELPER" --uid "$(id -u)" --display "${DISPLAY:-}" \
        --wayland-display "${WAYLAND_DISPLAY:-}" --xauthority "${XAUTHORITY:-}" \
        --session-type "${XDG_SESSION_TYPE:-}" -- "$@"
fi

launch_terminal_sudo "$@"
