#!/bin/bash
# Turn Midea AC OFF
# Usage: ha_ac_off.sh
# Requires: Docker access to homeassistant container, refresh token in .storage/auth
ENTITY="climate.152832117784908_climate"

TOKEN=$(docker exec homeassistant python3 -c "
import json, urllib.request, urllib.parse
with open('/config/.storage/auth') as f:
    auth = json.load(f)
for rt in auth['data']['refresh_tokens']:
    if rt['token_type'] == 'normal' and rt.get('last_used_at'):
        cid = rt.get('client_id', 'http://localhost:8123/')
        data = urllib.parse.urlencode({
            'grant_type': 'refresh_token',
            'refresh_token': rt['token'],
            'client_id': cid,
        }).encode()
        req = urllib.request.Request('http://localhost:8123/auth/token', data=data,
            headers={'Content-Type': 'application/x-www-form-urlencoded'})
        with urllib.request.urlopen(req) as resp:
            print(json.loads(resp.read())['access_token'])
        break
" 2>/dev/null)

curl -s -X POST \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d "{\"entity_id\": \"$ENTITY\", \"hvac_mode\": \"off\"}" \
  "http://localhost:8123/api/services/climate/set_hvac_mode"

echo "AC OFF at $(date)"
