#!/bin/sh
# Fetal Health launcher
#
# Runs the Flask app inside its private venv.
# Environment overrides can be set in /etc/<appname>/config.conf

APP_DIR="/usr/share/rms-fhd"
VENV="${APP_DIR}/venv"
CONF="/etc/rms-fhd/config.conf"

# Load config (safe key=value pairs only)
if [ -f "$CONF" ]; then
    # shellcheck disable=SC1090
    . "$CONF"
fi

FLASK_HOST="${FLASK_HOST:-127.0.0.1}"
FLASK_PORT="${FLASK_PORT:-8888}"
FLASK_DEBUG="${FLASK_DEBUG:-0}"

ENTRY="${APP_DIR}/run_app.py"
[ -f "$ENTRY" ] || ENTRY="${APP_DIR}/app/run_app.py"

if [ ! -f "$ENTRY" ]; then
    echo "ERROR: could not locate run_app.py under $APP_DIR" >&2
    exit 1
fi

if [ ! -x "${VENV}/bin/python" ]; then
    echo "ERROR: Python venv missing at $VENV" >&2
    echo "Try reinstalling the package." >&2
    exit 1
fi

export FLASK_APP="$ENTRY"
export FLASK_RUN_HOST="$FLASK_HOST"
export FLASK_RUN_PORT="$FLASK_PORT"

if [ "$FLASK_DEBUG" = "1" ]; then
    export FLASK_DEBUG=1
fi

cd "$APP_DIR"

if grep -q 'app\.run(' "$ENTRY" 2>/dev/null; then
    exec "${VENV}/bin/python" "$ENTRY" "$@"
else
    exec "${VENV}/bin/flask" run --host="$FLASK_HOST" --port="$FLASK_PORT" "$@"
fi
