#!/usr/bin/env bash

#https://developers.home-assistant.io/docs/api/rest/

source "${HOME}/.secrets"

while getopts "a:I:i:d:s:" flag; do
  case $flag in
    a)
      action="${OPTARG}"
      ;;
    I)
      identify_by="${OPTARG}"
      ;;
    i)
      identifier="${OPTARG}"
      ;;
    d)
      domain="${OPTARG}"
      ;;
    s)
      service="${OPTARG}"
      ;;
    *)
      printf '%s' "bad option: ${flag}"
      ;;
  esac
done

#echo "action: ${action}"
#echo "entity_id: ${entity_id}"

case "${action}" in
  "states")
    curl -s \
      -H "Authorization: Bearer ${HA_TOKEN}" \
      -H "Content-Type: application/json" \
      "${HA_URL}/api/${action}/${identifier}" | jq '.'
    ;;
  "services")
#    echo '{"entity_id": "'"${entity_id}"'"}'
    curl -s \
      -H "Authorization: Bearer ${HA_TOKEN}" \
      -H "Content-Type: application/json" \
      -d '{"'"${identify_by}"'": "'"${identifier}"'"}' \
      "${HA_URL}/api/${action}/${domain}/${service}" | jq '.'
    ;;
esac
