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

if [[ $# -ne 2 ]]; then
    echo "Usage: $0 <ROBOT_SN> <TABLE_NAME>" >&2
    exit 1
fi

BASE_URL="${BASE_URL:-https://pudu-api.tes.gd}"
USERNAME="${USERNAME:-admin}"
PASSWORD="${PASSWORD:-admin}"
ROBOT_SN="$1"
TABLE_NAME="$2"

TOKEN=$(curl -fsS -X POST "$BASE_URL/api/Auth/login" \
    -H "Content-Type: application/json" \
    -d "{\"username\":\"$USERNAME\",\"password\":\"$PASSWORD\"}" \
    | sed -n 's/.*"token":"\([^"]*\)".*/\1/p')

if [[ -z "$TOKEN" ]]; then
    echo "Login failed: could not extract token." >&2
    exit 1
fi

curl -fsS -X POST "$BASE_URL/api/Robots/add-command" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -d "{\"Sn\":\"$ROBOT_SN\",\"TargetPoint\":\"$TABLE_NAME\"}"
echo
