#!/usr/bin/env bash
# shellcheck disable=SC2024,SC1112  # logs stay user-owned on purpose; curly quotes are display text
# =============================================================================
#  DANKE://HMI — installer
#
#  From the website (nothing to download first):
#      curl -fsSL https://www.710hub.com/DankeHMI/install.sh | bash
#  From the unzipped folder:
#      ./install.sh
#
#  One password prompt. When it finishes, DANKE HMI is in your app menu and
#  its window opens with a QR code to scan. Run it again any time: it updates
#  in place and keeps your settings and paired phones.
#
#  Options:  --no-open   don't open the window at the end
#            --repair    (used by danke-hmi-repair) fix an existing install
# =============================================================================
set -Eeuo pipefail

VERSION="1.7.0"
ZIP_URL="${DANKE_ZIP_URL:-https://www.710hub.com/DankeHMI/downloads/DANKE-HMI-MOBILE-DECK-${VERSION}.zip}"
ZIP_SHA256="${DANKE_ZIP_SHA256:-1a71136fd7fa0eb853dd9674b59ceb139f06f35ea20c061e94f646ee9706d95c}"   # SHA-256 of downloads/DANKE-HMI-MOBILE-DECK-1.7.0.zip
PORT="${DANKE_PORT:-8765}"

APP="danke-hmi"
DATA="${XDG_DATA_HOME:-$HOME/.local/share}"
BASE="$DATA/$APP"
CONF="${XDG_CONFIG_HOME:-$HOME/.config}/$APP"
STATE="${XDG_STATE_HOME:-$HOME/.local/state}/$APP"
UNITS="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user"
BIN="$HOME/.local/bin"
LOG="$STATE/install.log"

MODE=install; OPEN=1
for arg in "$@"; do
  case "$arg" in
    --repair)  MODE=repair ;;
    --no-open) OPEN=0 ;;
    -h|--help) sed -n '2,19p' "${BASH_SOURCE[0]:-$0}" 2>/dev/null | sed 's/^# \{0,1\}//'; exit 0 ;;
  esac
done
# Test hooks (not for normal use): skip the root step / systemd in containers.
SKIP_SYSTEM="${DANKE_SKIP_SYSTEM:-0}"; SKIP_SYSTEMD="${DANKE_SKIP_SYSTEMD:-0}"

# ---- output ------------------------------------------------------------------
if [ -t 1 ]; then Y=$'\e[1;33m'; G=$'\e[32m'; R=$'\e[31m'; D=$'\e[2m'; B=$'\e[1m'; N=$'\e[0m'
else Y=""; G=""; R=""; D=""; B=""; N=""; fi
STEP=0; TOTAL=6
step() { STEP=$((STEP+1)); printf '\n%s[%d/%d]%s %s%s%s\n' "$Y" "$STEP" "$TOTAL" "$N" "$B" "$*" "$N"; echo "== [$STEP/$TOTAL] $*" >>"$LOG"; }
ok()   { printf '      %s✓%s %s\n' "$G" "$N" "$*"; }
note() { printf '      %s%s%s\n' "$D" "$*" "$N"; }
warn() { printf '      %s!%s %s\n' "$Y" "$N" "$*"; WARNINGS+=("$*"); }
die()  { printf '\n%s✗ %s%s\n' "$R" "$*" "$N"; printf '  Détails dans : %s\n' "$LOG"; printf '  Relance la même commande : elle reprend là où ça a coincé.\n\n'; exit 1; }
run()  { echo "\$ $*" >>"$LOG"; "$@" >>"$LOG" 2>&1; }      # quiet, logged
WARNINGS=(); KEEPALIVE=""; TMP=""
cleanup() { [ -n "$KEEPALIVE" ] && kill "$KEEPALIVE" 2>/dev/null; [ -n "$TMP" ] && rm -rf "$TMP"; return 0; }
trap cleanup EXIT
trap 'die "Arrêt inattendu à la ligne $LINENO."' ERR

mkdir -p "$STATE"; : >"$LOG"
printf '\n%s DANKE://HMI %s %s— installation\n' "$Y" "$VERSION" "$N"
printf '%s ════════════════════════════════════════%s\n' "$D" "$N"

[ "$(id -u)" -ne 0 ] || die "Lance cette commande en utilisateur normal, sans sudo. Le mot de passe sera demandé au bon moment."
[ "$(uname -s)" = Linux ] || die "DANKE HMI tourne sur Linux uniquement."

# =============================================================================
step "Analyse de ce PC"
# =============================================================================
# subshell: os-release defines its own VERSION, which must not clobber ours
OS_NAME="$( . /etc/os-release 2>/dev/null; echo "${PRETTY_NAME:-Linux}" )" || OS_NAME="Linux"
PM=none
for c in pacman apt-get dnf zypper; do command -v "$c" >/dev/null 2>&1 && { PM="$c"; break; }; done

DESK="${XDG_CURRENT_DESKTOP:-}"
[ -n "${HYPRLAND_INSTANCE_SIGNATURE:-}" ] && DESK="Hyprland"
[ -n "${SWAYSOCK:-}" ] && DESK="sway"
[ -n "${NIRI_SOCKET:-}" ] && DESK="niri"
GRAPHICAL=0; { [ -n "${WAYLAND_DISPLAY:-}" ] || [ -n "${DISPLAY:-}" ]; } && GRAPHICAL=1

# LAN subnet of the default route, e.g. 192.168.1.0/24 (for the firewall rule)
IFACE="$(ip -o -4 route show to default 2>/dev/null | awk '{for(i=1;i<=NF;i++) if($i=="dev"){print $(i+1);exit}}' || true)"
SUBNET=""
[ -n "$IFACE" ] && SUBNET="$(ip -o -4 route show dev "$IFACE" scope link 2>/dev/null | awk '$1 ~ /\// {print $1; exit}' || true)"
LAN_IP="$(ip -o -4 route get 1.1.1.1 2>/dev/null | awk '{for(i=1;i<=NF;i++) if($i=="src"){print $(i+1);exit}}' || true)"

OLD_VERSION="$(cat "$BASE/VERSION" 2>/dev/null || true)"
if [ -z "$OLD_VERSION" ] && [ -f "$BASE/config/mobile_ui.json" ]; then   # installs before 1.7
  OLD_VERSION="$(sed -n 's/.*"version": *"\([^"]*\)".*/\1/p' "$BASE/config/mobile_ui.json" | head -1 || true)"
fi

ok "$OS_NAME · ${DESK:-bureau inconnu} · gestionnaire de paquets : $PM"
[ -n "$LAN_IP" ] && ok "Réseau local : $LAN_IP${SUBNET:+ ($SUBNET)}" || warn "Pas de réseau local détecté. Le téléphone devra être sur le même Wi-Fi."
if [ "$MODE" = repair ]; then ok "Réparation de l'installation existante"
elif [ -n "$OLD_VERSION" ]; then ok "Mise à jour ${OLD_VERSION} → ${VERSION} (réglages et téléphones conservés)"
else ok "Nouvelle installation"; fi
case "$DESK" in Hyprland|sway|niri) ;; *) note "Fenêtres et raccourcis : meilleur support sur Hyprland, sway, niri. Le reste marche partout." ;; esac

# =============================================================================
step "Réglages système (mot de passe demandé une seule fois)"
# =============================================================================
case "$PM" in
  pacman)  PKGS="python python-evdev wtype grim libnotify playerctl wl-clipboard qrencode avahi nss-mdns curl" ;;
  apt-get) PKGS="python3 python3-venv python3-evdev wtype grim libnotify-bin playerctl wl-clipboard qrencode avahi-daemon libnss-mdns curl" ;;
  dnf)     PKGS="python3 python3-evdev wtype grim libnotify playerctl wl-clipboard qrencode avahi nss-mdns curl" ;;
  zypper)  PKGS="python3 python3-evdev wtype grim libnotify-tools playerctl wl-clipboard qrencode avahi nss-mdns curl" ;;
  *)       PKGS="" ;;
esac

ROOT_SCRIPT="$(mktemp)"
cat >"$ROOT_SCRIPT" <<'ROOT'
#!/usr/bin/env bash
# Everything that needs root, in one go. Args: PM "PKGS" SUBNET PORT
set -u
PM="$1"; PKGS="$2"; SUBNET="$3"; PORT="$4"
say() { echo "@@ $*"; }

# 1. packages — all at once, then one by one if a name doesn't exist on this distro
install_all() {
  case "$PM" in
    pacman)  pacman -S --needed --noconfirm $1 ;;
    apt-get) DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends $1 ;;
    dnf)     dnf install -y $1 ;;
    zypper)  zypper --non-interactive install --no-recommends $1 ;;
  esac
}
if [ -n "$PKGS" ]; then
  [ "$PM" = apt-get ] && apt-get update -qq
  if install_all "$PKGS"; then say "PKGS ok"
  else
    missing=""
    for p in $PKGS; do install_all "$p" >/dev/null 2>&1 || missing="$missing $p"; done
    say "PKGS partial$missing"
  fi
  systemctl enable --now avahi-daemon.service >/dev/null 2>&1 && say "AVAHI ok" || true
fi

# 2. virtual keyboard/mouse: /dev/uinput for the logged-in user.
#    TAG+="uaccess" = logind grants it to whoever sits at the machine, right now.
#    No 'input' group, no logout.
echo uinput > /etc/modules-load.d/danke-hmi-uinput.conf
modprobe uinput 2>/dev/null || true
cat > /etc/udev/rules.d/70-danke-hmi-uinput.rules <<'RULE'
# DANKE HMI: the user logged in at this machine may create virtual input devices.
KERNEL=="uinput", SUBSYSTEM=="misc", TAG+="uaccess", OPTIONS+="static_node=uinput"
RULE
udevadm control --reload-rules 2>/dev/null || true
udevadm trigger --action=change --sysname-match=uinput 2>/dev/null || true
udevadm settle 2>/dev/null || true
say "UINPUT rule"

# 3. firewall: open the port to the local network only, never to the internet
if [ -n "$SUBNET" ]; then
  if command -v ufw >/dev/null 2>&1 && ufw status 2>/dev/null | grep -q "Status: active"; then
    ufw allow from "$SUBNET" to any port "$PORT" proto tcp comment 'DANKE HMI (LAN)' >/dev/null && say "FW ufw:$SUBNET"
  elif command -v firewall-cmd >/dev/null 2>&1 && firewall-cmd --state >/dev/null 2>&1; then
    firewall-cmd --permanent --add-rich-rule="rule family=ipv4 source address=$SUBNET port port=$PORT protocol=tcp accept" >/dev/null \
      && firewall-cmd --reload >/dev/null && say "FW firewalld:$SUBNET"
  else
    say "FW none"
  fi
fi
ROOT

ROOT_OUT="$STATE/root.out"; : >"$ROOT_OUT"
if [ "$SKIP_SYSTEM" = 1 ]; then
  note "(étape système sautée : DANKE_SKIP_SYSTEM=1)"
else
  if command -v sudo >/dev/null 2>&1 && [ -r /dev/tty ]; then
    printf '      Paquets, clavier/souris virtuels, pare-feu. %sTon mot de passe :%s\n' "$B" "$N"
    # sudo reads the password from the terminal even when this script comes from curl | bash
    if ! sudo -v </dev/tty; then die "Mot de passe refusé ou sudo indisponible."; fi
    ( while true; do sudo -n true 2>/dev/null; sleep 50; done ) & KEEPALIVE=$!
    note "Installation des paquets… (1 à 3 min la première fois)"
    sudo bash "$ROOT_SCRIPT" "$PM" "$PKGS" "$SUBNET" "$PORT" >"$ROOT_OUT" 2>&1 </dev/null || true
  elif command -v pkexec >/dev/null 2>&1; then
    note "Une fenêtre va demander ton mot de passe."
    pkexec "$(command -v bash)" "$ROOT_SCRIPT" "$PM" "$PKGS" "$SUBNET" "$PORT" >"$ROOT_OUT" 2>&1 </dev/null || true
  else
    warn "Ni sudo ni pkexec : étape système sautée. Certaines fonctions manqueront."
  fi
  cat "$ROOT_OUT" >>"$LOG"
fi
rm -f "$ROOT_SCRIPT"

if grep -q '^@@ PKGS ok' "$ROOT_OUT"; then ok "Paquets système"
elif line="$(grep '^@@ PKGS partial' "$ROOT_OUT")"; then
  warn "Paquets introuvables :${line#@@ PKGS partial}. Le reste marche ; « Réparer » réessaiera."
  [ "$PM" = pacman ] && note "Si ça persiste : sudo pacman -Syu, puis Réparer."
elif [ -n "$PKGS" ] && [ "$SKIP_SYSTEM" != 1 ]; then warn "Paquets non installés (voir le journal)."; fi

FW_DONE="$(sed -n 's/^@@ FW \(ufw\|firewalld\):\(.*\)$/\1:\2/p' "$ROOT_OUT" | head -1 || true)"
if [ -n "$FW_DONE" ]; then echo "$FW_DONE" >"$STATE/firewall"; ok "Pare-feu : port $PORT ouvert pour le réseau local seulement (${FW_DONE#*:})"
elif grep -q '^@@ FW none' "$ROOT_OUT"; then ok "Pas de pare-feu actif à régler"
elif [ -z "$SUBNET" ]; then note "Pare-feu non touché (réseau local inconnu)"; fi

PY="$(command -v python3 || command -v python || true)"
[ -n "$PY" ] || die "Python 3 est introuvable et n'a pas pu être installé."
"$PY" -c 'import sys; sys.exit(0 if sys.version_info >= (3, 10) else 1)' \
  || die "Python 3.10 ou plus récent est nécessaire (trouvé : $("$PY" -V 2>&1))."

# =============================================================================
step "Fichiers de l'application"
# =============================================================================
HERE="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" 2>/dev/null && pwd || true)"
SRC=""
if [ "$MODE" = repair ]; then
  [ -f "$BASE/server/main.py" ] || die "Aucune installation à réparer. Lance l'installation complète."
  ok "Fichiers en place ($BASE)"
elif [ -n "$HERE" ] && [ -f "$HERE/app/server/main.py" ]; then
  SRC="$HERE"
  ok "Depuis le dossier $(basename "$HERE")"
else
  TMP="$(mktemp -d)"
  note "Téléchargement de DANKE HMI $VERSION…"
  if command -v curl >/dev/null 2>&1; then run curl -fL --retry 3 -o "$TMP/danke.zip" "$ZIP_URL" || die "Téléchargement impossible : $ZIP_URL"
  elif command -v wget >/dev/null 2>&1; then run wget -O "$TMP/danke.zip" "$ZIP_URL" || die "Téléchargement impossible : $ZIP_URL"
  else die "Ni curl ni wget pour télécharger."; fi
  if [ -n "$ZIP_SHA256" ]; then
    GOT="$(sha256sum "$TMP/danke.zip" | awk '{print $1}')"
    [ "$GOT" = "$ZIP_SHA256" ] || die "L'archive téléchargée ne correspond pas à l'empreinte attendue. Rien n'a été installé."
    ok "Archive vérifiée (SHA-256)"
  fi
  "$PY" - "$TMP/danke.zip" "$TMP" <<'PY' >>"$LOG" 2>&1 || die "Archive illisible."
import sys, zipfile
zipfile.ZipFile(sys.argv[1]).extractall(sys.argv[2])
PY
  FOUND="$(find "$TMP" -path '*/app/server/main.py' -print -quit || true)"
  SRC="${FOUND%/app/server/main.py}"
  [ -f "$SRC/app/server/main.py" ] || die "Archive incomplète."
  ok "Téléchargé et extrait"
fi

if [ -n "$SRC" ]; then
  [ "$SKIP_SYSTEMD" = 1 ] || systemctl --user stop danke-hmi.service >/dev/null 2>&1 || true
  mkdir -p "$BASE" "$CONF"
  # replace everything except the Python env (saves minutes on updates)
  find "$BASE" -mindepth 1 -maxdepth 1 ! -name .venv -exec rm -rf {} +
  cp -R "$SRC/app/." "$BASE/"
  cp "$SRC/install.sh" "$BASE/installer.sh"
  echo "$VERSION" >"$BASE/VERSION"
  chmod 755 "$BASE"/run.sh "$BASE"/setup-uinput.sh "$BASE"/bin/* "$BASE/installer.sh"
  ok "Copié dans $BASE"
fi

# User settings live in ~/.config and survive updates; they are linked into the app.
# Release metadata (mobile_ui.json…) is NOT in this list, so updates can refresh it.
USER_FILES="profiles streamdeck settings node known_nodes manual_nodes context_rules action_registry
  universal_decks node_decks node_groups plugins plugin_schema plugin_trust plugin_permissions_approved
  plugin_catalog widget_layouts automations automation_state event_bus events cross_node_rules skin personal"
for n in $USER_FILES; do
  f="$BASE/config/$n.json"
  [ -f "$f" ] || [ -f "$CONF/$n.json" ] || continue
  [ -f "$CONF/$n.json" ] || cp "$f" "$CONF/$n.json"
  ln -sfn "$CONF/$n.json" "$f"
done
[ -f "$CONF/paired_devices.json" ] || echo '{}' >"$CONF/paired_devices.json"
ln -sfn "$CONF/paired_devices.json" "$BASE/config/paired_devices.json"
ok "Réglages dans $CONF"

# =============================================================================
step "Moteur Python"
# =============================================================================
VENV="$BASE/.venv"
if [ -x "$VENV/bin/python" ] && ! "$VENV/bin/python" -c 'import sys' >/dev/null 2>&1; then rm -rf "$VENV"; fi
if [ ! -x "$VENV/bin/python" ]; then
  # --system-site-packages: reuse the distro's python-evdev (no compiler needed)
  run "$PY" -m venv --system-site-packages "$VENV" || die "Création de l'environnement Python impossible (sur Debian/Ubuntu : paquet python3-venv)."
fi
note "Installation des modules… (30 s à 2 min)"
run "$VENV/bin/python" -m pip install --disable-pip-version-check -q --upgrade pip || true
if run "$VENV/bin/python" -m pip install --disable-pip-version-check -q -r "$BASE/requirements.txt"; then
  ok "Modules installés"
else
  # evdev is the only module that may need a compiler; everything else is pure Python
  grep -v '^evdev' "$BASE/requirements.txt" >"$STATE/requirements-noevdev.txt"
  run "$VENV/bin/python" -m pip install --disable-pip-version-check -q -r "$STATE/requirements-noevdev.txt" \
    || die "Installation des modules Python impossible (connexion internet ?)."
  warn "Module evdev absent : souris via le bureau seulement, pas de glisser-déposer."
fi
"$VENV/bin/python" -c 'import fastapi, uvicorn, segno' >>"$LOG" 2>&1 || die "Modules Python incomplets."

# =============================================================================
step "Intégration au bureau"
# =============================================================================
mkdir -p "$BIN" "$UNITS" "$DATA/applications" "$DATA/icons/hicolor/scalable/apps" "$DATA/icons/hicolor/256x256/apps"

for f in "$BASE"/bin/danke-hmi-*; do ln -sfn "$f" "$BIN/$(basename "$f")"; done
rm -f "$BIN/danke-hmi"                                           # pre-1.7 leftover
ok "Commandes : danke-hmi-open, -repair, -uninstall, -pair, -doctor"

cat >"$UNITS/danke-hmi.service" <<EOF
[Unit]
Description=DANKE HMI — control this computer from your phone
After=graphical-session.target network-online.target
Wants=network-online.target
StartLimitIntervalSec=0

[Service]
Type=simple
WorkingDirectory=$BASE
Environment=DANKE_PORT=$PORT
ExecStart=$BASE/run.sh
Restart=on-failure
RestartSec=3

[Install]
WantedBy=default.target
EOF

cp "$BASE/web/icons/danke-hmi.svg" "$DATA/icons/hicolor/scalable/apps/danke-hmi.svg"
cp "$BASE/web/icons/danke-hmi-256.png" "$DATA/icons/hicolor/256x256/apps/danke-hmi.png"
cat >"$DATA/applications/danke-hmi.desktop" <<EOF
[Desktop Entry]
Type=Application
Version=1.5
Name=DANKE HMI
GenericName=Phone remote
GenericName[fr]=Télécommande téléphone
Comment=Control this computer from your phone: keyboard, mouse, windows, media
Comment[fr]=Piloter ce PC depuis ton téléphone : clavier, souris, fenêtres, média
Exec=$BIN/danke-hmi-open
Icon=danke-hmi
Terminal=false
Categories=Network;RemoteAccess;
Keywords=phone;remote;keyboard;mouse;deck;telephone;telecommande;clavier;souris;
StartupWMClass=danke-hmi
StartupNotify=true
Actions=restart;

[Desktop Action restart]
Name=Restart service
Name[fr]=Redémarrer le service
Exec=$BIN/danke-hmi-restart
EOF
command -v update-desktop-database >/dev/null 2>&1 && run update-desktop-database -q "$DATA/applications" || true
command -v gtk-update-icon-cache >/dev/null 2>&1 && run gtk-update-icon-cache -q -t -f "$DATA/icons/hicolor" || true
ok "DANKE HMI ajouté au menu des applications"
case ":$PATH:" in *":$BIN:"*) ;; *) note "Astuce : ~/.local/bin n'est pas dans ton PATH (le menu marche quand même)." ;; esac

# =============================================================================
step "Démarrage"
# =============================================================================
health() {
  "$PY" - "$PORT" >/dev/null 2>&1 <<'PY'
import sys, urllib.request
urllib.request.urlopen(f"http://127.0.0.1:{sys.argv[1]}/api/health", timeout=1)
PY
}
if [ "$SKIP_SYSTEMD" = 1 ]; then
  note "(systemd sauté : DANKE_SKIP_SYSTEMD=1)"
else
  run systemctl --user daemon-reload || die "systemd --user indisponible. Lance DANKE HMI à la main : $BASE/run.sh"
  run systemctl --user enable danke-hmi.service || true
  run systemctl --user restart danke-hmi.service || true
  for _ in $(seq 1 60); do health && break; sleep 0.5; done
  if ! health; then
    printf '\n%s--- journal du service ---%s\n' "$D" "$N"
    journalctl --user -u danke-hmi.service -n 20 --no-pager -o cat 2>/dev/null || true
    die "Le service ne répond pas."
  fi
  ok "Service démarré, et démarrera tout seul à chaque session"
fi

# Virtual mouse check. uaccess needs an active local session; over SSH it won't
# apply, so fall back to the 'input' group (that one needs a logout).
if [ -w /dev/uinput ]; then
  ok "Clavier et souris virtuels prêts (pas besoin de se reconnecter)"
elif [ "$SKIP_SYSTEM" != 1 ] && [ -e /dev/uinput ] && sudo -n true 2>/dev/null; then
  sudo -n usermod -aG input "$USER" >>"$LOG" 2>&1 || true
  warn "Souris virtuelle : déconnecte-toi puis reconnecte-toi une fois pour l'activer."
else
  note "Souris virtuelle : lance « Réparer » depuis la fenêtre DANKE HMI si elle ne marche pas."
fi

# =============================================================================
printf '\n%s ════════════════════════════════════════%s\n' "$D" "$N"
printf ' %s✓ DANKE HMI %s est installé.%s\n\n' "$G" "$VERSION" "$N"
if [ "${#WARNINGS[@]}" -gt 0 ]; then
  printf ' %sÀ savoir :%s\n' "$B" "$N"; for w in "${WARNINGS[@]}"; do printf '   • %s\n' "$w"; done; echo
fi
printf ' Ouvre %sDANKE HMI%s depuis le menu des applications' "$B" "$N"
case "$DESK" in Hyprland) printf ' (Super + Espace)';; esac
printf '.\n Scanne le QR avec ton téléphone. C’est tout.\n\n'
printf ' %sRéparer : danke-hmi-repair · Désinstaller : danke-hmi-uninstall%s\n\n' "$D" "$N"

if [ "$OPEN" = 1 ] && [ "$SKIP_SYSTEMD" != 1 ]; then
  if [ "$GRAPHICAL" = 1 ]; then
    "$BIN/danke-hmi-open" >/dev/null 2>&1 || true
  elif command -v qrencode >/dev/null 2>&1 && [ -n "$LAN_IP" ]; then
    # over SSH: show the QR right here
    CODE="$("$PY" - "$PORT" <<'PY' 2>/dev/null || true
import json, sys, urllib.request
print(json.load(urllib.request.urlopen(f"http://127.0.0.1:{sys.argv[1]}/api/pair/code", timeout=2))["code"])
PY
)"
    if [ -n "$CODE" ]; then
      printf ' Pas d’écran ici : scanne ce QR (code %s)\n' "$CODE"
      qrencode -t ANSIUTF8 "http://$LAN_IP:$PORT/?code=$CODE"
    fi
  fi
fi
trap - ERR
