#!/usr/bin/env bash
#
# Run the persistent Simulation Worker agent in a fresh loopback-only network
# namespace. The Unix socket remains reachable from Mission Core because the
# worker shares the host mount namespace while PX4/Gazebo have no routed NIC.

set -Eeuo pipefail

readonly EXPECTED_DISTRO="MissionCore-Sim"
readonly D_ROOT="/mnt/d/NDC_MISSIONCORE/simulation"
SOURCE_ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd -P)"
readonly SOURCE_ROOT
readonly MISSION_CORE_COMMIT="${1:-}"
readonly SOCKET_ROOT="/run/missioncore-sim"
readonly SOCKET_PATH="${SOCKET_ROOT}/worker.sock"
readonly ROS_SETUP="/opt/ros/jazzy/setup.bash"
readonly PX4_MSGS_SETUP="${D_ROOT}/build/ros2/px4_msgs/install/setup.bash"

if [[ -z "${MISSION_CORE_COMMIT}" ]]; then
    echo "usage: $0 <exact-40-character-mission-core-commit>" >&2
    exit 2
fi
if [[ "${SOURCE_ROOT}" != "${D_ROOT}/source/"* ]]; then
    echo "error: worker source generation must be staged below the reviewed D root" >&2
    exit 2
fi
if ! [[ "${MISSION_CORE_COMMIT}" =~ ^[a-f0-9]{40}$ ]]; then
    echo "error: Mission Core commit must contain exactly 40 lowercase hex characters" >&2
    exit 2
fi

if [[ "${MISSIONCORE_S1_NETNS:-0}" != "1" ]]; then
    if [[ "${EUID}" -ne 0 ]]; then
        echo "error: initial worker invocation must run as root to create the namespace" >&2
        exit 2
    fi
    if [[ "${WSL_DISTRO_NAME:-}" != "${EXPECTED_DISTRO}" ]]; then
        echo "error: expected WSL distro ${EXPECTED_DISTRO}" >&2
        exit 2
    fi
    install -d -m 0700 -o missioncore -g missioncore -- "${SOCKET_ROOT}"
    if [[ -e "${SOCKET_PATH}" && ! -S "${SOCKET_PATH}" ]]; then
        echo "error: worker socket path is occupied by a non-socket" >&2
        exit 2
    fi
    exec unshare --net -- bash -c '
        set -e
        ip link set lo up
        exec runuser -u missioncore -- env MISSIONCORE_S1_NETNS=1 "$@"
    ' bash "$0" "$@"
fi

if [[ "${EUID}" -eq 0 || "${WSL_DISTRO_NAME:-}" != "${EXPECTED_DISTRO}" ]]; then
    echo "error: worker agent escaped the reviewed worker identity" >&2
    exit 2
fi
if [[ ! -f "${ROS_SETUP}" || ! -f "${PX4_MSGS_SETUP}" ]]; then
    echo "error: reviewed ROS 2 Jazzy/px4_msgs runtime is incomplete" >&2
    exit 2
fi

set +u
# shellcheck disable=SC1090
source "${ROS_SETUP}"
# shellcheck disable=SC1090
source "${PX4_MSGS_SETUP}"
set -u

exec env \
    ROS_DOMAIN_ID=0 \
    PYTHONPATH="${SOURCE_ROOT}/src:${PYTHONPATH:-}" \
    python3 -m k1link.simulation.worker_agent \
    --socket "${SOCKET_PATH}" \
    --mission-core-commit "${MISSION_CORE_COMMIT}" \
    --lifecycle-profile "${SOURCE_ROOT}/simulation/s1/stock-rover-lifecycle.yaml"
