#!/bin/bash

# Tear down pairing between specified user and robot ID.
#
# Usage:
#   $ source teardown_pairing.sh <user_email> <robot_id>
#
# $1 - User email paired with the robot.
# $2 - Robot ID.
#
# Examples
#
#   $ source teardown_pairing.sh jesse@zoox.com 07cbecdf-cc41-4f47-b2c6-a56efe1059be

if [ "${ADMIN_GATEWAY_URL:-unset}" = unset ]
then
    echo "ADMIN_GATEWAY_URL is not set."
    echo "Please run set_gateway_urls.sh to configure Maestro URLs."
    return 1
fi

USER_EMAIL=$1
MAESTRO_ROBOT_ID=$2

# Query the created user and set MAESTRO_USER_ID environment variable
MAESTRO_USER_ID=$(curl -s -k -X GET \
    --header 'Accept: application/json' \
    "${ADMIN_GATEWAY_URL}/v1/users/?limit=50&email=${USER_EMAIL}" \
    | jq -r '.items | .[0] | .id')

if [ $MAESTRO_USER_ID = null ]
then
    echo "User ${USER_EMAIL} doesn't exist."
    return 1
fi

PAIRING_NAME=Pairing_${MAESTRO_USER_ID}_${MAESTRO_ROBOT_ID}

MAESTRO_PAIRING_ID=$(curl -s -k -X GET \
    "${ADMIN_GATEWAY_URL}/v1/pairings/?name=${PAIRING_NAME}&active_only=false&limit=50" \
    --header 'Accept: application/json' \
    | jq -r '.items | .[0] | .id')

if [ $MAESTRO_PAIRING_ID = null ]
then
    echo "Pairing ${PAIRING_NAME} doesn't exist."
    return 1
fi

echo Deleting pairing ID $MAESTRO_PAIRING_ID...
curl -s -k -X DELETE "${ADMIN_GATEWAY_URL}/v1/pairings/${MAESTRO_PAIRING_ID}" \
    --header 'Accept: application/json'

echo Done.
