#!/usr/bin/sh
#
# Copyright (c) 2026 Oninit LLC. All rights reserved.
#
# Oninit Logwalker - /usr/bin/logwalker wrapper
#
# Sources the Informix CSDK environment, then exec's the real binary
# under libexec.
#
# logwalker is dynamically linked against the Informix CSDK ESQL/C
# runtime (libthsql / libthos / libthgen / libthxa + libif*.so), which
# lives under $INFORMIXDIR/lib and $INFORMIXDIR/lib/esql — paths that
# are NOT in the system ld.so search list. The ripper reader and the
# crypto reader are statically linked into the binary, so the ONLY
# runtime library path that has to be resolved here is the CSDK's.
#
# Edit /etc/logwalker/environment to point at your CSDK install.

[ -f /etc/logwalker/environment ] && . /etc/logwalker/environment

# Preflight the CSDK runtime. Without this, a missing/mis-pointed CSDK
# makes the dynamic loader abort with a cryptic
#   /usr/libexec/logwalker/logwalker: error while loading shared
#   libraries: libthsql.so: cannot open shared object file
# that names the internal libexec path, not "logwalker". Catch it here
# and explain in human terms how to fix it.
#
# Resolvable means findable on the EFFECTIVE library path — every
# LD_LIBRARY_PATH entry, the INFORMIXDIR lib dirs, AND the ldconfig
# cache. (Don't check only under INFORMIXDIR: the informix user's
# profile commonly puts the CSDK on LD_LIBRARY_PATH while INFORMIXDIR
# points at the database server, which carries no client libs.)
lw_found=
lw_oifs=$IFS; IFS=:
for lw_d in $LD_LIBRARY_PATH "$INFORMIXDIR/lib/esql" "$INFORMIXDIR/lib"; do
	[ -n "$lw_d" ] && [ -e "$lw_d/libthsql.so" ] && { lw_found=1; break; }
done
IFS=$lw_oifs
[ -z "$lw_found" ] && command -v ldconfig >/dev/null 2>&1 && \
	ldconfig -p 2>/dev/null | grep -q 'libthsql\.so' && lw_found=1

if [ -z "$lw_found" ]; then
	echo "logwalker: Informix CSDK runtime not found (libthsql.so)." >&2
	echo "" >&2
	echo "  logwalker links the Informix CSDK ESQL/C libraries at runtime," >&2
	echo "  but libthsql.so was not found on LD_LIBRARY_PATH, under" >&2
	echo "  INFORMIXDIR (=${INFORMIXDIR:-unset}), or in the ldconfig cache." >&2
	echo "" >&2
	echo "  Edit /etc/logwalker/environment and set CSDK_DIR (or INFORMIXDIR)" >&2
	echo "  to a CSDK or full Informix install that provides libthsql.so" >&2
	echo "  under lib/esql/. logwalker must run on the source Informix" >&2
	echo "  server, where such an install is present." >&2
	exit 1
fi

exec /usr/libexec/logwalker/logwalker "$@"
