← back to Charge And Explore
scripts/tesla-await-and-register.sh
47 lines
#!/usr/bin/env bash
# Poll the Tesla Fleet partner-token endpoint until billing/Fleet-API access
# propagates (invalid_audience -> access_token), then run the one-time domain
# registration (POST /api/1/partner_accounts). Idempotent; safe to re-run.
set -u
cd "$(dirname "$0")/.." || exit 1
set -a; . ./.env; set +a
AUTH="https://fleet-auth.prd.vn.cloud.tesla.com/oauth2/v3/token"
DOMAIN="chargeandexplore.agentabrams.com"
REGIONS=(na eu)
MAX=120 # up to 120 tries
SLEEP=120 # every 2 min (~4h ceiling)
aud_for(){ case "$1" in cn) echo "https://fleet-api.prd.cn.vn.cloud.tesla.cn";; *) echo "https://fleet-api.prd.$1.vn.cloud.tesla.com";; esac; }
get_token(){
curl -s -X POST "$AUTH" -H 'content-type: application/x-www-form-urlencoded' \
--data-urlencode grant_type=client_credentials \
--data-urlencode "client_id=$TESLA_CLIENT_ID" \
--data-urlencode "client_secret=$TESLA_CLIENT_SECRET" \
--data-urlencode "scope=openid offline_access vehicle_device_data vehicle_location" \
--data-urlencode "audience=$1"
}
for i in $(seq 1 $MAX); do
for R in "${REGIONS[@]}"; do
AUD="$(aud_for "$R")"
RESP="$(get_token "$AUD")"
TOKEN="$(echo "$RESP" | python3 -c 'import sys,json;print(json.load(sys.stdin).get("access_token",""))' 2>/dev/null)"
if [ -n "$TOKEN" ]; then
echo "TOKEN MINTED region=$R aud=$AUD (attempt $i)"
echo "Registering partner account for domain=$DOMAIN ..."
REG="$(curl -s -X POST "$AUD/api/1/partner_accounts" \
-H "authorization: Bearer $TOKEN" -H 'content-type: application/json' \
-d "{\"domain\":\"$DOMAIN\"}")"
echo "REGISTER RESPONSE: $REG"
echo "DONE region=$R"
exit 0
fi
done
echo "attempt $i/$MAX: still invalid_audience (all regions) — sleeping ${SLEEP}s"
sleep "$SLEEP"
done
echo "GAVE UP after $MAX attempts — still not active. Re-run when billing shows active."
exit 2