#!/bin/bash
# Rosett-AI - Runtime wrapper
# Invoked as /opt/rosett-ai/bin/raictl, symlinked from /usr/local/bin/raictl
#
# 3.4.0 and x86_64-linux are substituted at build time by
# install_wrapper! in lib/rosett_ai/thor/tasks/build.rb
set -e

INSTALL_DIR="/opt/rosett-ai"
EMBEDDED_DIR="${INSTALL_DIR}/embedded"
EMBEDDED_BIN="${EMBEDDED_DIR}/bin"
EMBEDDED_LIB="${EMBEDDED_DIR}/lib"
APP_DIR="${INSTALL_DIR}/app"

# Ensure the embedded Ruby can find libruby.so
export LD_LIBRARY_PATH="${EMBEDDED_LIB}${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"

# Ensure the embedded Ruby can find its standard library
export RUBYLIB="${EMBEDDED_LIB}/ruby/3.4.0:${EMBEDDED_LIB}/ruby/3.4.0/x86_64-linux${RUBYLIB:+:$RUBYLIB}"

export PATH="${EMBEDDED_BIN}:${PATH}"
export GEM_HOME="${EMBEDDED_LIB}/ruby/gems/3.4.0"
export GEM_PATH="${GEM_HOME}"
export BUNDLE_GEMFILE="${APP_DIR}/Gemfile"
export BUNDLE_PATH="${APP_DIR}/vendor/bundle"
export BUNDLE_DEPLOYMENT="true"
# Per ci_hygiene rule_046: wrapper MUST set BUNDLE_WITHOUT explicitly.
# Mirrors lib/rosett_ai/thor/tasks/build.rb:442 (`--without development test
# build desktop engines`) so runtime Bundler skips exactly the groups
# excluded at build time. Never rely on .bundle/config surviving fpm.
export BUNDLE_WITHOUT="development:test:build:desktop:engines"

# Ensure UTF-8 locale (raictl requires it)
: "${LANG:=en_US.UTF-8}"
: "${LC_ALL:=$LANG}"
export LANG LC_ALL

# Preserve the user's working directory before cd-ing into the app tree.
# ProjectContext reads RAI_ORIGINAL_PWD to resolve the correct project.
export RAI_ORIGINAL_PWD="${PWD}"

cd "${APP_DIR}"
exec "${EMBEDDED_BIN}/ruby" -I"${APP_DIR}/lib" "${APP_DIR}/bin/raictl" "$@"
