#!/bin/sh CACHE_FILE="$XDG_CACHE_HOME/hass-scenes" TAB="$(printf '\t')" update_cache() { rm -f "$CACHE_FILE" curl -s -X GET \ -H "Authorization: Bearer $HASS_TOKEN" \ -H "Content-Type: application/json" \ "$HASS_SERVER/api/states" |\ jq --raw-output ' .[] | select(.entity_id | startswith("scene.")) | "\(.attributes.friendly_name)\t\(.entity_id)" ' > "$CACHE_FILE" } # update cache if it does not exist [ ! -e "$CACHE_FILE" ] && update_cache # update the cache if requested explicitly [ "$1" = "--update" ] && { update_cache exit } # update the cache if it is older than MAX_CACHE_AGE=$(( 60 * 60 * 24 )) # one day [ $(( $(date +%s) - $MAX_CACHE_AGE )) -gt $(date -r "$CACHE_FILE" +%s) ] && update_cache if [ $# -eq 0 ] ; then # pick a scene using rofi in dmenu mode scene="$(cat "$CACHE_FILE" |\ rofi \ -dmenu \ -display-columns 1 \ -display-column-separator "$TAB" |\ cut -d"$TAB" -f2 |\ jq --raw-input)" else # non interactive scene pick scene="$(cat "$CACHE_FILE" |\ grep -w "$*" | head -n1 |\ cut -d"$TAB" -f2 |\ jq --raw-input)" fi # exit if no scene was selected / found [ -z "$scene" ] && exit 0 jq -n --argjson scene "$scene" '{"entity_id": $scene}' |\ curl -s -X POST -d @- \ -H "Authorization: Bearer $HASS_TOKEN" \ -H "Content-Type: application/json" \ "$HASS_SERVER/api/services/scene/turn_on" > /dev/null