#!/bin/sh
# Launcher for the "Instalar ops-edge-agent" app menu entry.
#
# The goal is that a non-technical store employee never has to type a
# command — just click the app and, at most, type their password once.
#
# Preferred path: if a polkit authentication agent is actually running,
# `pkexec` shows a native "type your password" dialog with no terminal at
# all — the most professional-looking option, and what most modern desktops
# (GNOME, KDE, XFCE with their default session) provide out of the box.
#
# Fallback: `pkexec` with NO agent running hangs forever waiting on a
# graphical prompt that will never appear — confirmed live on a MATE/Mint
# desktop, where it froze the whole session. So we only take that path once
# we've confirmed an agent process exists; otherwise we fall back to a
# visible terminal that runs the command for them (they still only type
# their password, never a command).
set -eu

CMD='sudo ops-edge-agent setup; echo; read -r -p "Presiona Enter para cerrar..." _'

polkit_agent_running() {
  # Covers the agent shipped by GNOME, MATE, KDE, XFCE, LXDE/LXQt and
  # generic distros (Mint's mint-common ships its own with this name).
  for agent in \
    polkit-gnome-authentication-agent-1 \
    polkit-mate-authentication-agent-1 \
    polkit-kde-authentication-agent-1 \
    xfce-polkit \
    lxpolkit \
    lxqt-policykit-agent \
    ukui-polkit \
    mate-polkit \
    polkitd-agent; do
    if pgrep -x "$agent" >/dev/null 2>&1; then
      return 0
    fi
  done
  return 1
}

if command -v pkexec >/dev/null 2>&1 && command -v pgrep >/dev/null 2>&1 && polkit_agent_running; then
  exec pkexec ops-edge-agent setup
fi

for term in x-terminal-emulator gnome-terminal konsole xfce4-terminal mate-terminal xterm; do
  if command -v "$term" >/dev/null 2>&1; then
    case "$term" in
      gnome-terminal) exec gnome-terminal -- sh -c "$CMD" ;;
      konsole)        exec konsole -e sh -c "$CMD" ;;
      *)              exec "$term" -e sh -c "$CMD" ;;
    esac
  fi
done

# Last resort: no terminal emulator found either. Try pkexec anyway — worst
# case it hangs the way it used to, but there was no other option left.
exec pkexec ops-edge-agent setup
