#!/bin/sh
# `aeris` — the AERIS OS command-line tool.
#
# The deb installs this at /usr/bin/aeris and the Python under
# /usr/lib/AERIS OS/tools/. In a checkout it sits next to aeris_cli.py and works
# with no installation at all. Everything real lives in aeris_cli.py; this file
# exists only so that `aeris init` is a command and not a python3 invocation
# with a path in it.
set -eu

if ! command -v python3 >/dev/null 2>&1; then
    echo "aeris: python3 is required and was not found on PATH." >&2
    echo "       The AERIS brain tools are Python 3 standard library only;" >&2
    echo "       install python3 from your distribution and run this again." >&2
    exit 1
fi

self=$0
if command -v readlink >/dev/null 2>&1; then
    resolved=$(readlink -f "$0" 2>/dev/null) || resolved=$0
    self=$resolved
fi
here=$(dirname "$self")

if [ -n "${AERIS_TOOLS_DIR:-}" ] && [ -f "$AERIS_TOOLS_DIR/aeris_cli.py" ]; then
    exec python3 "$AERIS_TOOLS_DIR/aeris_cli.py" "$@"
fi

# The root override lets package-layout tests exercise the absolute paths.
launcher_root=${AERIS_LAUNCHER_ROOT:-}
appdir_tools=
appdir_legacy_tools=
if [ -n "${APPDIR:-}" ]; then
    appdir_tools="$APPDIR/usr/lib/AERIS OS/tools/aeris_cli.py"
    appdir_legacy_tools="$APPDIR/usr/lib/aeris-os/tools/aeris_cli.py"
fi

for candidate in \
    "$here/aeris_cli.py" \
    "$here/../lib/AERIS OS/tools/aeris_cli.py" \
    "$here/../lib/aeris-os/tools/aeris_cli.py" \
    "$appdir_tools" \
    "$appdir_legacy_tools" \
    "$launcher_root/usr/lib/AERIS OS/tools/aeris_cli.py" \
    "$launcher_root/usr/lib/aeris-os/tools/aeris_cli.py"
do
    if [ -n "$candidate" ] && [ -f "$candidate" ]; then
        exec python3 "$candidate" "$@"
    fi
done

echo "aeris: cannot find aeris_cli.py next to this launcher or under" >&2
echo "       /usr/lib/AERIS OS/tools or /usr/lib/aeris-os/tools." >&2
echo "       Set AERIS_TOOLS_DIR to the directory" >&2
echo "       holding aeris_cli.py and aeris_brain_mcp.py." >&2
exit 1
