#!/bin/bash

# Cancel the active mission for a robot name.
#
# Usage:
#   $ source cancel_mission.sh <robot_name>
#
# $1 - Which robot to cancel the mission
#
# Examples
#
#   $ source cancel_mission.sh kitt_01

export MAESTRO_ROBOT_NAME=$1

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 [ $MAESTRO_ROBOT_ID = null ]
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 [ $MAESTRO_ROBOT_ID = null ]
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 ACTIVE_MISSION_ID=$(curl -s -X GET \
    --header 'Accept: application/json' \
    "${ROBOT_GATEWAY_URL}/v1/robots/${MAESTRO_ROBOT_ID}/mission-queue?only_active=true" \
    | jq '.items[0].id')

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

export CANCELLED_MISSION_ID=$(curl -s -X PUT \
  --header 'Content-Type: application/json' \
  --header 'Accept: application/json' \
  -d '{"status": "CANCELLED"}' \
  "${ROBOT_GATEWAY_URL}/v1/robots/${MAESTRO_ROBOT_ID}/mission" \
  | jq '.id')

if [ -z ${CANCELLED_MISSION_ID} ]
then
    echo "Fail to cancel active mission for robot ${MAESTRO_ROBOT_ID}."
    return 1
else
    echo "Successfully cancelled mission id ${CANCELLED_MISSION_ID}" \
         "for robot id ${MAESTRO_ROBOT_ID}."
fi
