#!/bin/bash

# ProxMenux Monitor AppImage Entry Point
# This script is executed when the AppImage is run

# Get the directory where this AppImage is mounted
APPDIR="$(dirname "$(readlink -f "${0}")")"

export PATH="${APPDIR}/usr/bin:${PATH}"
export LD_LIBRARY_PATH="${APPDIR}/usr/lib/x86_64-linux-gnu:${APPDIR}/usr/lib:${APPDIR}/lib/x86_64-linux-gnu:${APPDIR}/lib:${LD_LIBRARY_PATH}"

# Select the native dependency tree matching the host interpreter.  PVE 8
# uses CPython 3.11 and PVE 9 uses CPython 3.13; both runtimes are bundled in
# the same AppImage so its gevent HTTPS/WSS server is independent of the
# Python version used by the GitHub Actions build runner.
PYTHON_ABI="$(python3 -c 'import sys; print(f"cp{sys.version_info.major}{sys.version_info.minor}")' 2>/dev/null || true)"
PYTHON_ABI_DIR="${APPDIR}/usr/lib/python3/vendor/${PYTHON_ABI}"
PYTHON_COMMON_DIRS="${APPDIR}/usr/lib/python3/dist-packages:${APPDIR}/usr/lib/python3/site-packages"

case "$PYTHON_ABI" in
    cp311|cp313)
        if [ -d "$PYTHON_ABI_DIR" ]; then
            export PYTHONPATH="${PYTHON_ABI_DIR}:${PYTHON_COMMON_DIRS}${PYTHONPATH:+:${PYTHONPATH}}"
        else
            echo "⚠️  Bundled Python runtime ${PYTHON_ABI} is missing; HTTPS/WSS may be unavailable" >&2
            export PYTHONPATH="${PYTHON_COMMON_DIRS}${PYTHONPATH:+:${PYTHONPATH}}"
        fi
        ;;
    *)
        echo "⚠️  Unsupported host Python ABI '${PYTHON_ABI:-unknown}'; expected cp311 (PVE 8) or cp313 (PVE 9)" >&2
        export PYTHONPATH="${PYTHON_COMMON_DIRS}${PYTHONPATH:+:${PYTHONPATH}}"
        ;;
esac

# Change to the AppImage directory
cd "${APPDIR}"

# Check for translation argument
if [[ "$1" == "--translate" ]]; then
    echo "🌐 Starting ProxMenux Translation Service..."
    exec python3 "${APPDIR}/usr/bin/translate_cli.py" "${@:2}"
else
    echo "🚀 Starting ProxMenux Monitor Dashboard..."
    echo ""
    
    echo "🔧 Hardware monitoring tools:"
    [ -x "${APPDIR}/usr/bin/ipmitool" ] && echo "  ✅ ipmitool available" || echo "  ⚠️  ipmitool not available"
    [ -x "${APPDIR}/usr/bin/sensors" ] && echo "  ✅ sensors available" || echo "  ⚠️  sensors not available"
    [ -x "${APPDIR}/usr/bin/upsc" ] && echo "  ✅ upsc available" || echo "  ⚠️  upsc not available"
    
    if [ -x "${APPDIR}/usr/bin/ipmitool" ]; then
        if ldd "${APPDIR}/usr/bin/ipmitool" 2>/dev/null | grep -q "libfreeipmi.so.17 => not found"; then
            echo "  ⚠️  libfreeipmi.so.17 not found - ipmitool may not work"
        elif ldd "${APPDIR}/usr/bin/ipmitool" 2>/dev/null | grep -q "libfreeipmi.so.17"; then
            echo "  ✅ libfreeipmi.so.17 loaded successfully"
        fi
    fi
    
    echo ""
    
    # Start the Flask server
    exec python3 "${APPDIR}/usr/bin/flask_server.py"
fi
