#!/usr/bin/env bash
# The weather on BlueRune's bar: the temperature, a symbol for the sky, and the last few
# readings as a small chart. Asks wttr.in; offline, it keeps showing the last reading and says
# how old it is. Run it every 15 minutes (docs/extensions.md has a systemd timer for that).
#
#   BLUERUNE_WEATHER_PLACE   the place to ask about (Oslo, "New York"); wttr.in guesses
#                            from the connection without it
#
# BlueRune runs this script again when the item is used: a press opens the forecast in the
# browser, and Refresh in its menu (a right press) asks again now.
set -uo pipefail

place=${BLUERUNE_WEATHER_PLACE:-}
where=${place// /+}
# Each place's readings apart, so the chart never joins two places.
state=${XDG_STATE_HOME:-$HOME/.local/state}/bluerune-weather/${where:-here}
mkdir -p "$state"
self=$(realpath "$0")
# The argument in single quotes, for `sh -c`.
quoted() { printf "'%s'" "${1//\'/\'\\\'\'}"; }
# BlueRune runs the command from its own environment, not the timer's: it carries the place.
command="BLUERUNE_WEATHER_PLACE=$(quoted "$place") $(quoted "$self")"

# Used from the bar: BlueRune says how.
case "${BLUERUNE_ACTION:-}" in
    activate) exec xdg-open "https://wttr.in/$where" ;;
    menu) [[ ${BLUERUNE_VALUE:-} == refresh ]] || exit 0 ;;
    "") ;;
    *) exit 0 ;;
esac

# A Material Symbols name for wttr.in's words for the sky.
symbol() {
    local sky=${1,,}
    case $sky in
        *thunder*) echo thunderstorm ;;
        *snow* | *sleet* | *blizzard* | *ice*) echo weather_snowy ;;
        *rain* | *drizzle* | *shower*) echo rainy ;;
        *fog* | *mist* | *haze*) echo foggy ;;
        *partly*) echo partly_cloudy_day ;;
        *cloud* | *overcast*) echo cloud ;;
        *sun* | *clear*) echo sunny ;;
        *) echo thermostat ;;
    esac
}

set_item() { # icon text tooltip hue
    local content
    # The readings so far, oldest first, for the chart.
    content=$(printf '{"chart": [%s]}' "$(paste -sd, "$state/readings" 2>/dev/null)")
    bluerunectl ext set weather --name Weather --icon "$1" --text "$2" --tooltip "$3" ${4:+--hue "$4"} \
        --content "$content" --menu "Refresh=refresh" --menu - --menu "${place:-Your location} from wttr.in" \
        --on-click "$command" >/dev/null
}

# Sky | temperature | feels like, such as "Light rain|+12°C|+9°C".
if line=$(curl -fsS --max-time 10 "https://wttr.in/$where?format=%C|%t|%f" 2>/dev/null) && [[ $line == *"|"*"|"* ]]; then
    IFS='|' read -r sky temperature feels <<<"$line"
    # wttr.in may end the sky's words with a space.
    sky=${sky%"${sky##*[![:space:]]}"}
    temperature=${temperature#+}
    printf '%s\n%s\n%s\n%s\n' "$sky" "$temperature" "${feels#+}" "$(date +%H:%M)" >"$state/last"
    # Twelve readings: three hours at one every 15 minutes.
    { tail -n 11 "$state/readings" 2>/dev/null; echo "${temperature//[^0-9.-]/}"; } >"$state/readings.new" && mv "$state/readings.new" "$state/readings"
    set_item "$(symbol "$sky")" "${temperature%[CF]}" "$sky, $temperature. Feels like ${feels#+}."
elif [[ -s $state/last ]]; then
    { read -r sky; read -r temperature; read -r feels; read -r at; } <"$state/last"
    # Old news: the warning color, and the tooltip says from when.
    set_item "$(symbol "$sky")" "${temperature%[CF]}" "Could not reach wttr.in. This is the reading from $at: $sky, $temperature." warning
else
    set_item cloud_off "–" "Could not reach wttr.in. The weather shows once the computer is online."
fi
