#!/usr/bin/env bash
# Start sesinetd (required for Apprentice), then launch Houdini.
set -euo pipefail

HFS="${HFS:-/opt/hfs}"
# distrobox forwards the host shell's environment into the container. On a
# host that sets LD_LIBRARY_PATH itself (e.g. NixOS), that leaks in libs
# built for the host's glibc, which crash Houdini's binaries at load time.
# houdini_setup only ever *prepends* to LD_LIBRARY_PATH, so start it clean.
unset LD_LIBRARY_PATH
# houdini_setup isn't written for strict mode (unset vars, commands like
# `which java` that are expected to fail silently), so relax around the source.
_p="$PWD"; cd "${HFS}"
set +euo pipefail; source ./houdini_setup >/dev/null; set -euo pipefail
cd "${_p}"

if ! pgrep -x sesinetd >/dev/null 2>&1; then
    # sesinetd runs as www-data (dropped from root by sudo below); a license
    # file bind-mounted from the host belongs to the host user instead and
    # isn't writable by www-data, which makes activation silently fail
    # ("Failed to open license file" in /var/log/sidefx/sesinetd.log, visible
    # in the GUI as an unrelated-looking "Success (curl error 0)" error).
    sudo chmod 666 /usr/lib/sesi/licenses 2>/dev/null || true
    # If self-signed cert generation ever gets interrupted, it leaves 0-byte
    # cert/key files behind; sesinetd then spins at ~100% CPU retrying
    # against them forever instead of regenerating. Clear those out first.
    for f in /usr/lib/sesi/ssl/auth.cert /usr/lib/sesi/ssl/auth.priv; do
        [ -e "$f" ] && [ ! -s "$f" ] && sudo rm -f "$f"
    done
    sudo /usr/lib/sesi/sesinetd >/dev/null 2>&1 &
    sleep 2
fi

exec "${@:-houdinifx}"
