#!/bin/bash
# Force umnode to load packaged rootfs libs (OpenSSL 3), never host OpenSSL 1.1.
DIR=$(CDPATH= cd -- "$(dirname "$0")" && pwd)
export UMGRID_BINDIR=$DIR
REAL=$DIR/umnode.real
if [ ! -x "$REAL" ]; then
  echo "umnode: missing $REAL" >&2
  exit 127
fi
# shellcheck disable=SC1091
if [ -f "$DIR/../linux/libpath.sh" ]; then
  . "$DIR/../linux/libpath.sh"
elif [ -f /data/umapp/linux/libpath.sh ]; then
  . /data/umapp/linux/libpath.sh
fi
if command -v umgrid_export_packaged_libs >/dev/null 2>&1; then
  umgrid_export_packaged_libs
else
  _root=$(CDPATH= cd -- "$DIR/../../.." && pwd)
  UMGRID_LDSO=$_root/usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
  [ -f "$UMGRID_LDSO" ] || UMGRID_LDSO=$_root/usr/lib/aarch64-linux-gnu/ld-linux-aarch64.so.1
  UMGRID_LIBPATH="$_root/usr/lib/x86_64-linux-gnu:$_root/usr/lib/aarch64-linux-gnu:$_root/lib/x86_64-linux-gnu:$_root/lib/aarch64-linux-gnu:$DIR/lib"
  UMGRID_ROOTFS=$_root
  unset _root
fi
# Outside chroot is unsupported for normal service use.
if [ -n "${UMGRID_ROOTFS:-}" ] && [ "$UMGRID_ROOTFS" != "/" ]; then
  if [ "${UMGRID_ALLOW_HOST_RUN:-0}" != "1" ]; then
    cat >&2 <<'EOF'
umnode: 检测到在宿主机上直接运行（未进入 rootfs chroot）。

请改用：
  systemctl status umgrid
  systemctl restart umgrid

浏览器访问: http://服务器IP/
调试库依赖时可临时: UMGRID_ALLOW_HOST_RUN=1 ./umnode
EOF
    exit 1
  fi
  # Host debug only: use packaged ld.so so OpenSSL 3 / glibc match the binary.
  if [ -n "${UMGRID_LDSO:-}" ] && [ -f "$UMGRID_LDSO" ] && [ -n "${UMGRID_LIBPATH:-}" ]; then
    exec "$UMGRID_LDSO" --library-path "$UMGRID_LIBPATH" "$REAL" "$@"
  fi
  echo "umnode: packaged dynamic linker not found" >&2
  exit 127
fi
# Inside chroot: exec the ELF directly. Using ld.so --library-path here has been
# observed to leave umnode stuck in D-state on aarch64 (port half-open, 502).
if [ -n "${UMGRID_LIBPATH:-}" ]; then
  export LD_LIBRARY_PATH="$UMGRID_LIBPATH${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
fi
exec "$REAL" "$@"
