#!/usr/bin/env bash
#
# run — the agent, straight out of the repository.
#
# No install, no service unit and no Central: this starts the edge agent with
# deploy/edge.standalone.yaml and keeps everything it writes under build/edge/,
# which is gitignored. Arguments are passed through to `geo-mlops-edge`, so any
# subcommand works and a config of your own still wins.
#
#   ./run                      # same as ./run run
#   ./run status               # ask the running agent (from a second terminal)
#   ./run queue --limit 5
#   ./run run --config /etc/geo-mlops/edge.yaml

ROOT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" || exit; pwd)

function print_message
{
    # shellcheck disable=SC2145
    echo -e "\033[32m$@\033[0m"
}

CONFIG="${GEO_EDGE_CONFIG:-$ROOT_DIR/deploy/edge.standalone.yaml}"
STATE_DIR="${GEO_EDGE_DATA_DIR:-$ROOT_DIR/build/edge}"

ARGS=("$@")
if [[ ${#ARGS[@]} -eq 0 ]]; then
    ARGS=("run")
fi

# A --config anywhere means the caller chose one; do not second-guess it.
for arg in "${ARGS[@]}"; do
    if [[ "$arg" == "--config" ]]; then
        CONFIG=""
        break
    fi
done
if [[ -n "$CONFIG" ]]; then
    ARGS+=("--config" "$CONFIG")
fi

# The sample's collector reads and writes relative paths, and the agent resolves
# them against its working directory -- which uv pins to ROOT_DIR.
mkdir -p "$STATE_DIR/incoming"
export GEO_EDGE_DATA_DIR="$STATE_DIR"

print_message "geo-mlops-edge ${ARGS[*]}"

# `run` is a foreground service, so the agent goes in the background here and
# the signals are forwarded to it. Killing this wrapper without forwarding
# leaves the agent alive holding the queue database and the API port, and the
# next ./run then fails to bind for a reason that looks nothing like the cause.
# Isolated like pytest.sh: a leaked PYTHONPATH (a sourced ROS environment, say)
# would otherwise pull foreign packages into the agent.
PYTHONPATH= uv --directory "$ROOT_DIR" run geo-mlops-edge "${ARGS[@]}" &
AGENT_PID=$!

trap 'kill -INT "$AGENT_PID" 2>/dev/null' INT
trap 'kill -TERM "$AGENT_PID" 2>/dev/null' TERM

# A trap makes `wait` return 128+signal while the agent is still shutting down.
# Wait again until it is actually reaped, so the exit code is the agent's --
# 3 means it asked to be restarted (see deploy/systemd/geo-mlops-edge.service).
wait "$AGENT_PID"
STATUS=$?
while [[ $STATUS -gt 128 ]] && kill -0 "$AGENT_PID" 2>/dev/null; do
    wait "$AGENT_PID"
    STATUS=$?
done

exit $STATUS
