#!/bin/bash

# Create an exclusive pairing with specified user and robot ID.
# Sets $MAESTRO_PAIRING_ID and $MAESTRO_ROBOT_ID environment variable.
#
# Usage:
#   $ source pair_user_robot.sh <user_email> <robot_id>
#
# $1 - User email to be paired with the robot.
# $2 - Robot ID to be paired with.
#
# Examples
#
#   $ source pair_user_robot.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
export MAESTRO_ROBOT_ID=$2

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

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

echo Creating pairing...
curl -s -k -X POST "${ADMIN_GATEWAY_URL}/v1/pairings/" \
    --header 'Content-Type: application/json' \
    --header 'Accept: application/json' \
    -d "{
        \"description\": \"Test pairing\",
        \"keyword\": \"exclusive\",
        \"name\": \"Pairing_${MAESTRO_USER_ID}_${MAESTRO_ROBOT_ID}\",
        \"ordered\": true,
        \"robotId\": \"$MAESTRO_ROBOT_ID\",
        \"userId\": \"$MAESTRO_USER_ID\"
        }"

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

if [ $MAESTRO_PAIRING_ID = null ]
then
    unset MAESTRO_PAIRING_ID
    echo "Failed to create pairing."
    return 1
else
    echo "Pairing is created or already exists. Pairing ID: $MAESTRO_PAIRING_ID"
    return 0
fi
