#!/usr/bin/env bash
#
# Enter a fresh loopback-only namespace and execute the S1B stock-rover
# lifecycle as the unprivileged missioncore worker identity.

set -Eeuo pipefail

readonly EXPECTED_DISTRO="MissionCore-Sim"
readonly D_ROOT="/mnt/d/NDC_MISSIONCORE/simulation"
readonly SOURCE_ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd -P)"
readonly RUN_ID="${1:-}"
readonly MISSION_CORE_COMMIT="${2:-}"

if [[ -z "${RUN_ID}" || -z "${MISSION_CORE_COMMIT}" ]]; then
    echo "usage: $0 <run-id> <exact-40-character-mission-core-commit>" >&2
    exit 2
fi
if [[ "${SOURCE_ROOT}" != "${D_ROOT}/source/"* ]]; then
    echo "error: S1B 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 S1B invocation must run as root to create the network namespace" >&2
        exit 2
    fi
    if [[ "${WSL_DISTRO_NAME:-}" != "${EXPECTED_DISTRO}" ]]; then
        echo "error: expected WSL distro ${EXPECTED_DISTRO}" >&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: S1B inner lifecycle escaped the reviewed worker identity" >&2
    exit 2
fi

exec env \
    PYTHONPATH="${SOURCE_ROOT}/src" \
    python3 "${SOURCE_ROOT}/simulation/s1/stock_rover_lifecycle.py" \
    --run-id "${RUN_ID}" \
    --mission-core-commit "${MISSION_CORE_COMMIT}" \
    --lifecycle-profile "${SOURCE_ROOT}/simulation/s1/stock-rover-lifecycle.yaml"
