#!/bin/bash

# La aplicación necesita privilegios de root (carga módulos y ajusta permisos de
# /dev/videoN). Si se la lanza sin ellos, se relanza con sudo, igual que hace el
# lanzador del menú (Exec=sudo ipwebcam).
if [ "$EUID" -ne 0 ]; then
    exec sudo /usr/local/bin/ipwebcam
fi

# --- Notificaciones fiables desde script con sudo (X11/Wayland, sudo/pkexec) ---
notify_user() {
  local title="$1"
  local message="$2"
  local icon="$3"

  # Detectar usuario gráfico original
  local TARGET_USER=""
  if [ -n "$SUDO_USER" ] && [ "$SUDO_USER" != "root" ]; then
    TARGET_USER="$SUDO_USER"
  elif [ -n "$PKEXEC_UID" ]; then
    TARGET_USER="$(getent passwd "$PKEXEC_UID" | cut -d: -f1)"
  else
    TARGET_USER="$(logname 2>/dev/null || who | awk '{print $1; exit}' || id -un)"
  fi

  # Si no logramos detectar usuario, abortar silenciosamente
  [ -z "$TARGET_USER" ] && return 0

  local TARGET_UID
  TARGET_UID="$(id -u "$TARGET_USER" 2>/dev/null || echo "")"
  [ -z "$TARGET_UID" ] && return 0

  # Leer entorno de la sesión del usuario
  local USER_DISPLAY USER_WAYLAND USER_DBUS USER_HOME
  USER_DISPLAY="$(sudo -u "$TARGET_USER" printenv DISPLAY 2>/dev/null)"
  USER_WAYLAND="$(sudo -u "$TARGET_USER" printenv WAYLAND_DISPLAY 2>/dev/null)"
  USER_DBUS="$(sudo -u "$TARGET_USER" printenv DBUS_SESSION_BUS_ADDRESS 2>/dev/null)"
  USER_HOME="$(getent passwd "$TARGET_USER" | cut -d: -f6)"

  # Fallbacks si faltan variables
  [ -z "$USER_DBUS" ] && USER_DBUS="unix:path=/run/user/${TARGET_UID}/bus"
  # XDG_RUNTIME_DIR ayuda con algunos setups
  local USER_RUNTIME="/run/user/${TARGET_UID}"

  # Si no hay DISPLAY ni WAYLAND_DISPLAY, intentar valores razonables
  if [ -z "$USER_DISPLAY" ] && [ -z "$USER_WAYLAND" ]; then
    # Es habitual que al menos uno exista; si no, probamos defaults
    USER_WAYLAND="wayland-0"
    USER_DISPLAY=":0"
  fi

  # Urgencia e icono por defecto
  local URGENCY="-u critical"
  [ -z "$icon" ] && icon="/usr/share/icons/notify.png"

  # Ejecutar notify-send como el usuario gráfico, inyectando el entorno necesario
  sudo -u "$TARGET_USER" env -i \
    DISPLAY="$USER_DISPLAY" \
    WAYLAND_DISPLAY="$USER_WAYLAND" \
    DBUS_SESSION_BUS_ADDRESS="$USER_DBUS" \
    XDG_RUNTIME_DIR="$USER_RUNTIME" \
    HOME="$USER_HOME" \
    PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" \
    notify-send $URGENCY -i "$icon" "$title" "$message" >/dev/null 2>&1 || true
}
# -------------------------------------------------------------------------------

function _help_es {
  notify_user "CÁMARA DEL TELÉFONO, CÓMO USAR" \
"☛ Primero, instala la app IP WEBCAM en tu móvil.  
☛ Luego, ábrela y pulsa “Iniciar servidor” (abajo del todo).  
☛ Después, introduce la IP de tu teléfono en la Quirinux IP Webcam.  
  Se cargarán los módulos necesarios (haz clic en aceptar), y finalmente  
  se te notificará que la cámara está conectada
  (en tu móvil verás “video connections: 1”).  
☛ Ahora puedes seleccionar PhoneCam en Tahoma2D
  (pulsa Refresh si no aparece)." "/usr/share/icons/notify.png"
}

function _help_en {
  notify_user "PHONE CAMERA, HOW TO USE" \
"☛ First, install the IP WEBCAM app on your phone.  
☛ Then, open it and tap “Start server” (at the very bottom).  
☛ After that, enter your phone’s IP address into Quirinux IP Webcam.  
  The required modules will be loaded (click accept), and finally  
  you will be notified that the camera is connected 
  (on your phone you’ll see “video connections: 1”).  
☛ Now you can select PhoneCam in Tahoma2D 
  (press Refresh if it doesn't appear)." "/usr/share/icons/notify.png"
}

function _help_gl {
  notify_user "CÁMARA DO TELÉFONO, COMO USAR" \
"☛ Primeiro, instala a app IP WEBCAM no teu móbil.  
☛ Despois, ábrea e preme en “Iniciar servidor” (ao fondo de todo).  
☛ Logo, introduce a IP do teu móbil en Quirinux IP Webcam.  
  Cargaranse os módulos necesarios (preme en aceptar), e finalmente  
  notificarase que a cámara está conectada
  (no móbil verás “video connections: 1”).  
☛ Agora podes seleccionar PhoneCam en Tahoma2D 
  (preme Refresh se non aparece)." "/usr/share/icons/notify.png"
}

function _help_pt {
  notify_user "CÂMERA DO TELEFONE, COMO USAR" \
"☛ Primeiro, instale o app IP WEBCAM no seu celular.  
☛ Depois, abra e toque em “Iniciar servidor” (lá embaixo).  
☛ Em seguida, insira o IP do seu celular no Quirinux IP Webcam.  
  Os módulos necessários serão carregados (clique em aceitar), e finalmente  
  você será notificado de que a câmera está conectada
  (no celular verá “video connections: 1”).  
☛ Agora você pode selecionar PhoneCam no Tahoma2D 
  (clique em Refresh se não aparecer)." "/usr/share/icons/notify.png"
}

function _help_fr {
  notify_user "CAMÉRA DU TÉLÉPHONE, COMMENT FAIRE" \
"☛ D’abord, installez l’app IP WEBCAM sur votre téléphone.  
☛ Ensuite, ouvrez-la et appuyez sur “Démarrer le serveur” (tout en bas).  
☛ Puis, entrez l’adresse IP de votre téléphone dans Quirinux IP Webcam.  
  Les modules nécessaires seront chargés (cliquez sur accepter), et enfin  
  vous serez notifié que la caméra est connectée
  (sur votre téléphone, vous verrez “video connections: 1”).  
☛ Maintenant, vous pouvez sélectionner PhoneCam dans Tahoma2D
  (cliquez sur Refresh si elle n’apparaît pas)." "/usr/share/icons/notify.png"
}

function _help_it {
  notify_user "FOTOCAMERA DEL TELEFONO, COME USARE" \
"☛ Prima, installa l’app IP WEBCAM sul tuo telefono.  
☛ Poi aprila e tocca “Avvia server” (in fondo alla schermata).  
☛ Dopo, inserisci l’indirizzo IP del telefono in Quirinux IP Webcam.  
  Verranno caricati i moduli necessari (clicca su accetta), e infine  
  riceverai una notifica che la fotocamera è connessa
  (sul telefono vedrai “video connections: 1”).  
☛ Ora puoi selezionare PhoneCam in Tahoma2D
  (clicca su Refresh se non appare)." "/usr/share/icons/notify.png"
}

function _help_de {
  notify_user "HANDYKAMERA, ANWENDUNG" \
"☛ Installiere zuerst die App IP WEBCAM auf deinem Handy.  
☛ Öffne sie dann und tippe auf „Server starten“ (ganz unten).  
☛ Danach gibst du die IP-Adresse deines Handys in Quirinux IP Webcam ein.  
  Die benötigten Module werden geladen (auf „Akzeptieren“ klicken), und schließlich  
  wirst du benachrichtigt, dass die Kamera verbunden ist
  (auf dem Handy steht „video connections: 1“).  
☛ Jetzt kannst du PhoneCam in Tahoma2D auswählen
  (klicke auf Refresh, wenn es nicht erscheint)." "/usr/share/icons/notify.png"
}

function _lang() {
  ORIGINAL_LANG=$(locale | grep ^LANG= | cut -d= -f2)
  SHORT_LANG=$(echo "$ORIGINAL_LANG" | cut -d_ -f1)

  case "$SHORT_LANG" in
    es) _help_es ;;
    en) _help_en ;;
    gl) _help_gl ;;
    pt) _help_pt ;;
    fr) _help_fr ;;
    it) _help_it ;;
    de) _help_de ;;
    *)  _help_en ;;
  esac

  export LANG="$ORIGINAL_LANG"
  export LC_ALL="$ORIGINAL_LANG"

  cd /usr/local/bin
  # Aquí sí corre como root
  python3 ./ipwebcam.py
}

_lang
