#!/usr/bin/env bash
set -euo pipefail

RED='\033[0;31m'
NC='\033[0m' # No Color

# see if FORCE_MAIN_AI flag is set
is_force_on_main_ai=false
for var in "$@"
do
    if [ "$var" = "FORCE_MAIN_AI" ]; then
        is_force_on_main_ai=true
    fi;
done

if [ "${ZOOX_MACHINE_ROLE:=unset}"  == "ai" -a "$is_force_on_main_ai" == "false" ]; then
    echo ""
    echo ""
    echo "------------- Coredash should not be run on Main AI -------------"
    echo "Use FORCE_MAIN_AI flag to force run it."
    echo "Example : bazel run //continuum:launch_coredash -- FORCE_MAIN_AI"
    echo -e "${RED}WARNING: CoreDash is not designed to be run on the main AI computer.  Running on main AI will affect system performance.${NC}"
    echo ""
    echo ""
    exit 1
fi;
if [ "$ZOOX_MACHINE_ROLE" == "ai" -a "$is_force_on_main_ai" == "true" ]; then
  echo -e "${RED}WARNING: CoreDash is not designed to be run on the main AI computer.  Running on main AI will affect system performance.${NC}"
fi;

# Set the DDS initial peers to the default values + the main-ai so we don't depend on multicast
export NDDS_DISCOVERY_PEERS=builtin.udpv4://239.255.0.1,builtin.udpv4://127.0.0.1,builtin.shmem://,builtin.udpv4://192.168.3.2

# Build the command line as an array:
LAUNCH_CD_CMD=(
    "../coredash_build/launch_coredash"
    "-ZFR"
    "-LOCAL_MISSION_SIDE_HUSTLE"
    "-WINDOWED"
    "-MAESTRO"
    "-DAY_NIGHT_AUTO"
)

# Conditionally add the imagery option, depending on whether there's an
# imagery or not (e.g. get_imagery returns the empty string when
# default_imagery_name is missing, see CLM-10230)
MAP2D=$(mapping/imagery/get_imagery --get map2d)
if [ ! -z ${MAP2D} ]; then
    LAUNCH_CD_CMD+=("-IMAGERY_DIR" "${MAP2D}")
fi

# Add all arguments to this script to the command line:
LAUNCH_CD_CMD+=("$@")

# Run the command
"${LAUNCH_CD_CMD[@]}"
