#!/usr/bin/env bash
# SPDX-License-Identifier: GPL-3.0-only
# Copyright (C) 2026 Hugo Antonio Sepulveda Manriquez / NeatNerds
#
# Wrapper script for the packaged openproject-mcp server.
# Uses the embedded Ruby and vendored gems — no system Ruby required.
#
# The embedded Ruby is compiled with --prefix pointing at a staging dir
# (now deleted).  This wrapper overrides all path resolution so the
# binary finds its libs, stdlib, and gems at the installed location.
#
# 3.4.0 and x86_64-linux are substituted at build time by
# packaging/build.sh by querying RbConfig::CONFIG on the embedded Ruby
# binary in the staging tree (see also rosett-ai's wrapper.sh.template
# which uses the same pattern).
set -e

INSTALL_DIR="/opt/openproject-mcp"
EMBEDDED_DIR="${INSTALL_DIR}/ruby"
EMBEDDED_BIN="${EMBEDDED_DIR}/bin"
EMBEDDED_LIB="${EMBEDDED_DIR}/lib"

RUBY_ABI="3.4.0"
RUBY_ARCH="x86_64-linux"

# Shared library (libruby.so)
export LD_LIBRARY_PATH="${EMBEDDED_LIB}${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}"

# Ruby standard library (overrides baked-in staging prefix in RbConfig)
export RUBYLIB="${EMBEDDED_LIB}/ruby/${RUBY_ABI}:${EMBEDDED_LIB}/ruby/${RUBY_ABI}/${RUBY_ARCH}${RUBYLIB:+:${RUBYLIB}}"

# Gem and Bundler paths
export PATH="${EMBEDDED_BIN}:${PATH}"
export GEM_HOME="${EMBEDDED_LIB}/ruby/gems/${RUBY_ABI}"
export GEM_PATH="${GEM_HOME}"

# Bundler env vars — explicit per ci_hygiene rule_046.
# Never rely on .bundle/config surviving fpm packaging.
export BUNDLE_GEMFILE="${INSTALL_DIR}/Gemfile"
export BUNDLE_PATH="${INSTALL_DIR}/vendor/bundle"
export BUNDLE_DEPLOYMENT="true"
export BUNDLE_WITHOUT="development:test:mutation"

# UTF-8 locale (MCP stdio servers may emit non-ASCII payloads)
: "${LANG:=C.UTF-8}"
: "${LC_ALL:=${LANG}}"
export LANG LC_ALL

cd "${INSTALL_DIR}"
exec "${EMBEDDED_BIN}/ruby" "${INSTALL_DIR}/bin/openproject-mcp" "$@"
