post_install() {
    :
#!/bin/bash
# NextAnalyzer: después de instalar o actualizar (postinst de deb, %post de rpm, post_install y
# post_upgrade de pacman). electron-builder lo usa como plantilla: aquí no se escriben variables
# entre llaves.
APP=/opt/NextAnalyzer
BIN="$APP/nextanalyzer"
UNIT_SOURCE="$APP/resources/linux/nextanalyzer.service"
UNIT=/etc/systemd/system/nextanalyzer.service
ENROLL_FILE=/etc/nextanalyzer/enroll.conf

# Lo mismo que la plantilla de electron-builder: enlace en /usr/bin y chrome-sandbox.
ln -sf "$BIN" /usr/bin/nextanalyzer
if ! { [[ -L /proc/self/ns/user ]] && unshare --user true; } 2>/dev/null; then
  chmod 4755 "$APP/chrome-sandbox" || true
else
  chmod 0755 "$APP/chrome-sandbox" || true
fi
if hash update-mime-database 2>/dev/null; then update-mime-database /usr/share/mime || true; fi
if hash update-desktop-database 2>/dev/null; then update-desktop-database /usr/share/applications || true; fi

# Carpeta de datos (solo root) y servicio de systemd.
install -d -m 0700 /var/lib/nextanalyzer
install -m 0644 "$UNIT_SOURCE" "$UNIT"
SYSTEMD=0
if [ -d /run/systemd/system ]; then
  SYSTEMD=1
  systemctl daemon-reload || true
  systemctl enable nextanalyzer.service || true
fi

# Alta silenciosa, si viene el código por variable o por fichero:
#   sudo NEXTANALYZER_ENROLL_CODE=XXXX-XXXX NEXTANALYZER_GROUP=Oficina apt install ./nextanalyzer.deb
#   /etc/nextanalyzer/enroll.conf con líneas ENROLL_CODE=XXXX-XXXX y GROUP=Oficina (se borra al leerlo)
CODE="$NEXTANALYZER_ENROLL_CODE"
GROUP="$NEXTANALYZER_GROUP"
if [ -z "$CODE" ] && [ -f "$ENROLL_FILE" ]; then
  CODE=$(sed -n 's/^ENROLL_CODE=//p' "$ENROLL_FILE" | head -n 1 | tr -d '[:space:]"')
  GROUP=$(sed -n 's/^GROUP=//p' "$ENROLL_FILE" | head -n 1 | tr -d '"')
fi
if [ -f "$ENROLL_FILE" ]; then
  shred -u "$ENROLL_FILE" 2>/dev/null || rm -f "$ENROLL_FILE"
  rmdir /etc/nextanalyzer 2>/dev/null || true
fi
if [ -n "$CODE" ]; then
  [ "$SYSTEMD" = "1" ] && systemctl stop nextanalyzer.service 2>/dev/null
  /bin/bash "$APP/resources/linux/enroll.sh" "$CODE" "$GROUP"
  RESULT=$?
  if [ "$RESULT" != "0" ]; then
    echo "NextAnalyzer: el alta ha terminado con el código $RESULT (desktop-base.md §6.1)." >&2
    echo "Repítela con: sudo bash $APP/resources/linux/enroll.sh XXXX-XXXX" >&2
  fi
fi

if [ "$SYSTEMD" = "1" ]; then
  systemctl restart nextanalyzer.service || true
else
  echo "NextAnalyzer: este sistema no usa systemd; el servicio no se ha arrancado." >&2
fi
exit 0

}
post_upgrade() {
    :
#!/bin/bash
# NextAnalyzer: después de instalar o actualizar (postinst de deb, %post de rpm, post_install y
# post_upgrade de pacman). electron-builder lo usa como plantilla: aquí no se escriben variables
# entre llaves.
APP=/opt/NextAnalyzer
BIN="$APP/nextanalyzer"
UNIT_SOURCE="$APP/resources/linux/nextanalyzer.service"
UNIT=/etc/systemd/system/nextanalyzer.service
ENROLL_FILE=/etc/nextanalyzer/enroll.conf

# Lo mismo que la plantilla de electron-builder: enlace en /usr/bin y chrome-sandbox.
ln -sf "$BIN" /usr/bin/nextanalyzer
if ! { [[ -L /proc/self/ns/user ]] && unshare --user true; } 2>/dev/null; then
  chmod 4755 "$APP/chrome-sandbox" || true
else
  chmod 0755 "$APP/chrome-sandbox" || true
fi
if hash update-mime-database 2>/dev/null; then update-mime-database /usr/share/mime || true; fi
if hash update-desktop-database 2>/dev/null; then update-desktop-database /usr/share/applications || true; fi

# Carpeta de datos (solo root) y servicio de systemd.
install -d -m 0700 /var/lib/nextanalyzer
install -m 0644 "$UNIT_SOURCE" "$UNIT"
SYSTEMD=0
if [ -d /run/systemd/system ]; then
  SYSTEMD=1
  systemctl daemon-reload || true
  systemctl enable nextanalyzer.service || true
fi

# Alta silenciosa, si viene el código por variable o por fichero:
#   sudo NEXTANALYZER_ENROLL_CODE=XXXX-XXXX NEXTANALYZER_GROUP=Oficina apt install ./nextanalyzer.deb
#   /etc/nextanalyzer/enroll.conf con líneas ENROLL_CODE=XXXX-XXXX y GROUP=Oficina (se borra al leerlo)
CODE="$NEXTANALYZER_ENROLL_CODE"
GROUP="$NEXTANALYZER_GROUP"
if [ -z "$CODE" ] && [ -f "$ENROLL_FILE" ]; then
  CODE=$(sed -n 's/^ENROLL_CODE=//p' "$ENROLL_FILE" | head -n 1 | tr -d '[:space:]"')
  GROUP=$(sed -n 's/^GROUP=//p' "$ENROLL_FILE" | head -n 1 | tr -d '"')
fi
if [ -f "$ENROLL_FILE" ]; then
  shred -u "$ENROLL_FILE" 2>/dev/null || rm -f "$ENROLL_FILE"
  rmdir /etc/nextanalyzer 2>/dev/null || true
fi
if [ -n "$CODE" ]; then
  [ "$SYSTEMD" = "1" ] && systemctl stop nextanalyzer.service 2>/dev/null
  /bin/bash "$APP/resources/linux/enroll.sh" "$CODE" "$GROUP"
  RESULT=$?
  if [ "$RESULT" != "0" ]; then
    echo "NextAnalyzer: el alta ha terminado con el código $RESULT (desktop-base.md §6.1)." >&2
    echo "Repítela con: sudo bash $APP/resources/linux/enroll.sh XXXX-XXXX" >&2
  fi
fi

if [ "$SYSTEMD" = "1" ]; then
  systemctl restart nextanalyzer.service || true
else
  echo "NextAnalyzer: este sistema no usa systemd; el servicio no se ha arrancado." >&2
fi
exit 0

}
pre_remove() {
    :
#!/bin/bash
# NextAnalyzer: antes de quitar el paquete (prerm de deb, %preun de rpm, pre_remove de pacman).
# En una actualización solo para el servicio (deb) o no hace nada (rpm: el %post de la versión nueva
# ya lo ha reiniciado; pacman no llama a pre_remove al actualizar). Al desinstalar: para el servicio,
# deshace todo lo aplicado (DNS, cortafuegos, políticas de navegador, autoridad local), avisa a la API,
# quita el servicio, la vigilancia del DNS, el agente de Wazuh que instaló y sus datos.
APP=/opt/NextAnalyzer
DATA=/var/lib/nextanalyzer

case "$1" in
  upgrade|failed-upgrade|deconfigure)
    systemctl stop nextanalyzer.service 2>/dev/null || true
    exit 0
    ;;
esac
if [[ "$1" =~ ^[0-9]+$ ]] && [ "$1" -ge 1 ]; then
  exit 0
fi

# Desinstalación protegida por la organización (desktop-base.md §3, punto 7): el servicio sale con 3
# si no se permite (salvo que la pidiera la API). Un prerm que falla detiene la desinstalación en deb y
# rpm. Cualquier otro código (el servicio no arranca) la deja seguir.
ELECTRON_RUN_AS_NODE=1 NODE_ENV=production timeout 60 "$APP/nextanalyzer"   "$APP/resources/app.asar.unpacked/out/service/service/main.js" --uninstall-check >/dev/null 2>&1
if [ "$?" = "3" ]; then
  echo "NextAnalyzer: la organización ha protegido la desinstalación de este equipo. Pide a un administrador que la permita desde el panel o que retire el equipo." >&2
  exit 1
fi

SYSTEMD=0
[ -d /run/systemd/system ] && SYSTEMD=1
if [ "$SYSTEMD" = "1" ]; then
  systemctl disable --now nextanalyzer.service 2>/dev/null || true
fi

# Deshace lo aplicado y avisa a la API (5 s como mucho), con el propio servicio.
ELECTRON_RUN_AS_NODE=1 NODE_ENV=production timeout 180 "$APP/nextanalyzer" \
  "$APP/resources/app.asar.unpacked/out/service/service/main.js" --uninstalled || true

# Red de seguridad por si el paso anterior no ha podido: solo lo que es del agente.
if [ "$SYSTEMD" = "1" ]; then
  systemctl disable --now nextanalyzer-dns-guard.timer 2>/dev/null || true
fi
rm -f /etc/systemd/system/nextanalyzer-dns-guard.timer /etc/systemd/system/nextanalyzer-dns-guard.service
if [ -e /etc/systemd/resolved.conf.d/90-nextanalyzer.conf ]; then
  rm -f /etc/systemd/resolved.conf.d/90-nextanalyzer.conf
  systemctl try-restart systemd-resolved.service 2>/dev/null || true
fi
if [ -e /etc/NetworkManager/conf.d/90-nextanalyzer.conf ]; then
  rm -f /etc/NetworkManager/conf.d/90-nextanalyzer.conf
  systemctl try-reload-or-restart NetworkManager.service 2>/dev/null || true
fi
if [ -e "$DATA/resolv.conf.previous" ] || [ -L "$DATA/resolv.conf.previous" ]; then
  mv -f "$DATA/resolv.conf.previous" /etc/resolv.conf
fi
nft delete table inet nextanalyzer 2>/dev/null || true
for tool in iptables ip6tables; do
  if hash "$tool" 2>/dev/null; then
    "$tool" -D OUTPUT -j NEXTANALYZER 2>/dev/null
    "$tool" -F NEXTANALYZER 2>/dev/null
    "$tool" -X NEXTANALYZER 2>/dev/null
  fi
done

# Agente de Wazuh: solo si lo instaló NextAnalyzer. El gestor de paquetes está ocupado con esta
# desinstalación, así que se quita después, desde una unidad aparte que espera a que termine.
if [ -f "$DATA/wazuh-installed-by-agent" ] && [ "$SYSTEMD" = "1" ]; then
  # Reintenta cada 10 s durante 10 min mientras el gestor siga ocupado; si el paquete ya no está, para.
  systemd-run --unit=nextanalyzer-wazuh-removal --collect /bin/bash -c \
    'for i in $(seq 60); do sleep 10; if hash dpkg 2>/dev/null; then dpkg -s wazuh-agent 2>/dev/null | grep -q "^Status: install ok installed" || exit 0; elif hash rpm 2>/dev/null; then rpm -q wazuh-agent >/dev/null 2>&1 || exit 0; fi; if hash apt-get 2>/dev/null; then apt-get -y -o DPkg::Lock::Timeout=60 purge wazuh-agent && exit 0; elif hash zypper 2>/dev/null; then zypper --non-interactive remove wazuh-agent && exit 0; elif hash dnf 2>/dev/null; then dnf -y remove wazuh-agent && exit 0; elif hash yum 2>/dev/null; then yum -y remove wazuh-agent && exit 0; else rpm -e wazuh-agent && exit 0; fi; done' \
    2>/dev/null || true
fi

rm -f /etc/systemd/system/nextanalyzer.service
if [ "$SYSTEMD" = "1" ]; then
  systemctl daemon-reload 2>/dev/null || true
fi
# Datos y el OpenH264 de Cisco del acceso remoto (carpeta legible por la sesión).
rm -rf "$DATA" /var/lib/nextanalyzer-openh264
exit 0

}
post_remove() {
    :
#!/bin/bash
# NextAnalyzer: después de quitar el paquete (postrm de deb, %postun de rpm, post_remove de pacman).
# Lo mismo que la plantilla de electron-builder: quita el enlace de /usr/bin si ya no apunta a nada.
# electron-builder lo usa como plantilla: aquí no se escriben variables entre llaves.
if [ -L /usr/bin/nextanalyzer ] && [ ! -e /usr/bin/nextanalyzer ]; then
  rm -f /usr/bin/nextanalyzer
fi
if hash update-desktop-database 2>/dev/null; then update-desktop-database /usr/share/applications || true; fi
exit 0

}
