#!/bin/bash

hass_weather_cache="${HOME}/.cache/hass_weather.json"

update_cache_json(){
  weather_summary="$( hass-cli -a states -i sensor.weather_summary | jq -r '.attributes' )"
  if [[ -z "${weather_summary}" ]];then
    return 1
  fi
  condition="$( jq -r '.condition' <<< ""${weather_summary}"" )"
  condition_code="$( jq -r '.condition_code' <<< ""${weather_summary}"" )"
  current_temp="$( jq -r '.current_temp' <<< ""${weather_summary}"" )"
  feels_temp="$( jq -r '.feels_temp' <<< ""${weather_summary}"" )"
  min_temp="$( jq -r '.min_temp' <<< ""${weather_summary}"" )"
  max_temp="$( jq -r '.max_temp' <<< ""${weather_summary}"" )"
  humidity="$( jq -r '.humidity' <<< ""${weather_summary}"" )"
  updated="$(date '+%Y-%m-%d, %H:%M')"

  case "${condition_code}" in
  #https://openweathermap.org/weather-conditions#Weather-Condition-Codes-2
    (2[0-9][0-9])
      condition_icon=''
      ;;
    (3[0-9][0-9])
      condition_icon=''
      ;;
    (5[0-9][0-9])
      condition_icon=''
      ;;
    (6[0-9][0-9])
      condition_icon=''
      ;;
    (7[0-9][0-9])
      condition_icon='▒'
      ;;
    800)
      condition_icon=''
      ;;
    (80[0-9])
      condition_icon=''
      ;;
  esac

  jq -n \
    --arg condition "${condition}" \
    --arg current_temp "${current_temp}" \
    --arg feels_temp "${feels_temp}" \
    --arg min_temp "${min_temp}" \
    --arg max_temp "${max_temp}" \
    --arg humidity "${humidity}" \
    --arg icon "${condition_icon}" \
    --arg updated "${updated}" \
    '{condition: $condition,current_temp: $current_temp,feels_temp: $feels_temp,min_temp: $min_temp,max_temp: $max_temp,humidity: $humidity,icon: $icon,updated: $updated}' | tee "${hass_weather_cache}" >/dev/null

}

if [[ ! $(find "${hass_weather_cache}" -cmin -60 -print 2>/dev/null) ]]; then
#  if ! ping -w 15 -c 5 hass.pogmom.me;then
#    exit 1
#  fi
  update_cache_json
fi

cat "${hass_weather_cache}"
