#!/bin/bash

set -Eeu -o pipefail

VALUE_COLOR=${color:-$(xrescat i3xrocks.value.color "#D8DEE9")}
VALUE_FONT=${font:-$(xrescat i3xrocks.value.font "Source Code Pro Medium 13")}
BUTTON="${button:-}"

# Information on the various formats: https://github.com/chubin/wttr.in
VALUE_WEATHER_FORMAT=${weather_format:-$(xrescat i3xrocks.weather.format "1")}
VALUE_WEATHER_FORMAT="?format=${VALUE_WEATHER_FORMAT}"

# Determine units to use for temperature
# We don't supply a default here because wttr.in is "smart" enough to choose for us
ACTION_WEATHER_UNIT=""
WEATHER_UNIT=${weather_unit:-$(xrescat i3xrocks.weather.units "")}
if [ -n "${WEATHER_UNIT}" ]; then
    ACTION_WEATHER_UNIT="?${WEATHER_UNIT}"
    WEATHER_UNIT="&${WEATHER_UNIT}"
fi

# Defaults to IP address location
VALUE_WEATHER_LOCATION=${weather_location:-$(xrescat i3xrocks.weather.location "")}
VALUE_WEATHER_ERROR_MESSAGE=${error_message:-$(xrescat i3xrocks.weather.error_message $'\u26D4')}
# --fail: an HTTP error status (an unknown location, rate limiting, a server
# error) counts as a failure, so the body of wttr.in's error page never
# reaches the bar. An HTML page served with a success status is not weather
# either.
if ! WEATHER=$(curl -sS --fail "https://wttr.in/${VALUE_WEATHER_LOCATION}${VALUE_WEATHER_FORMAT}${WEATHER_UNIT}") \
    || echo "${WEATHER}" | grep -q -P "Unknown\slocation" \
    || echo "${WEATHER}" | grep -q -i -P "^\s*<(!doctype|html)"; then
    WEATHER="${VALUE_WEATHER_ERROR_MESSAGE}"
else
    # The bar reads the line as Pango markup: escape the characters in the
    # reply that it would take as markup.
    WEATHER=$(printf '%s' "${WEATHER}" | sed -e 's/&/\&amp;/g' -e 's/</\&lt;/g' -e 's/>/\&gt;/g')
fi

# wttr.in pads its output for terminal alignment (for example two or three
# spaces after the condition icon). Collapse each run of whitespace to a single
# space and trim the ends so the bar shows compact text.
shopt -s extglob
WEATHER="${WEATHER//+([[:space:]])/ }"
WEATHER="${WEATHER# }"
WEATHER="${WEATHER% }"

echo "<span font_desc=\"${VALUE_FONT}\" color=\"${VALUE_COLOR}\">${WEATHER}</span>"

if [ ! "x${BUTTON}" == "x" ]; then
    ACTION=$(xrescat i3xrocks.action.weather "xdg-open https://wttr.in/${VALUE_WEATHER_LOCATION}${ACTION_WEATHER_UNIT}")
    /usr/bin/i3-msg -q exec "$ACTION"
fi
