#!/bin/sh
# @weather [location] - condition, temperature and local time
#
# In chat:  @weather            -> default: Bangkok and Warsaw
#           @weather Wroclaw     -> just that location
#           @weather New York    -> the whole argument arrives as "$1"
#
# Weather comes from wttr.in. Its %T (time) field is served from a cache
# and goes stale, so we take only the timezone name (%Z, which is
# static) from wttr.in and compute the current local time with date.

fmt='%l:+%c+%t+%Z'

one() {
	loc=$(printf '%s' "$1" | tr ' ' '+')
	out=$(curl -fsS --max-time 8 "https://wttr.in/${loc}?format=${fmt}") || {
		printf 'weather: lookup failed for %s\n' "$1"
		return
	}
	tz=${out##* }            # last token: timezone name, e.g. Asia/Bangkok
	wx=${out% *}             # the rest: location, condition, temperature
	case "$tz" in
		*/*)
			now=$(TZ="$tz" date '+%H:%M')
			printf '%s, %s\n' "$wx" "$now"
			;;
		*)
			printf '%s\n' "$out"   # no usable timezone: show as-is
			;;
	esac
}

if [ -n "$1" ]; then
	one "$1"
else
	one Bangkok
	one Warsaw
fi
