#!/bin/bash

# Request a utility mission for a robot name.
#
# Usage:
#   $ source request_utility_mission.sh <robot_name> <mission_type>
#
# $1 - Robot name to request a mission for.
# $2 - Which mission type to request
#      Utility mission types available:
#          - RANDOM_DESTINATION_SF_EXTENDED
#          - RANDOM_ROUTE_SF_EXTENDED
#          - RANDOM_DESTINATION_SLAC
#          - RANDOM_ROUTE_SLAC
#
# Examples
#
#   $ source request_utility_mission.sh kitt_01 RANDOM_DESTINATION_SF_EXTENDED

export MAESTRO_ROBOT_NAME=$1
export MAESTRO_MISSION_TYPE=$2

export MAESTRO_ROBOT_ID=$(curl -s -X GET \
  --header 'Accept: application/json' \
  "https://ki-robot-info.zooxlabs.com/v1/robot/?name=${MAESTRO_ROBOT_NAME}" \
  | jq -r '.items[0].id')

if [ -z ${MAESTRO_ROBOT_ID} ]
then
    echo "Fail to get robot id for robot ${MAESTRO_ROBOT_NAME}."
    return 1
else
    echo "${MAESTRO_ROBOT_NAME}'s id is ${MAESTRO_ROBOT_ID}."
fi

export ROBOT_GATEWAY_URL=$(curl -s -X GET \
  --header 'Accept: application/json' \
  "https://ralph.zooxlabs.com/v1/robots/${MAESTRO_ROBOT_ID}/services/maestro-robot-gateway" \
  | jq -r '.url')

if [ -z ${ROBOT_GATEWAY_URL} ]
then
    echo "Fail to get robot gateway url for robot id ${MAESTRO_ROBOT_ID}."
    return 1
else
    echo "${MAESTRO_ROBOT_NAME}'s robot gateway url is ${ROBOT_GATEWAY_URL}."
fi

export MAESTRO_MISSION_ID=$(curl -s -X POST \
  --header 'Content-Type: application/json' \
  --header 'Accept: application/json' \
  -d "{
       \"missionType\": \"${MAESTRO_MISSION_TYPE}\"
     }" \
  "${ROBOT_GATEWAY_URL}/v1/robots/${MAESTRO_ROBOT_ID}/mission-request" \
  | jq '.id'
  )

if [ -z ${MAESTRO_MISSION_ID} ]
then
    echo "Fail to request ${MAESTRO_MISSION_TYPE} mission for robot ${MAESTRO_ROBOT_ID}."
    return 1
else
    echo "Successfully requested ${MAESTRO_MISSION_TYPE} mission ${MAESTRO_MISSION_ID}" \
         "for robot id ${MAESTRO_ROBOT_ID}."
fi
