#!/bin/sh

# Displays today's precipication chance, and daily low and high.
# Usually intended for the statusbar.

url="${WTTRURL:-wttr.in}"
weatherreport="${XDG_CACHE_HOME:-$HOME/.cache}/weatherreport"

# Get a weather report from 'wttr.in' and save it locally.
getforecast() { timeout --signal=1 2s curl -sf "$url/$LOCATION" > "$weatherreport" || exit 1; }

# Check if forecast is fresh (less than 30 minutes old)
checkforecast() {
	[ -s "$weatherreport" ] || return 1
	last_modified=$(stat -c %Y "$weatherreport" 2>/dev/null) || return 1
	now=$(date +%s)
	age=$((now - last_modified))
	[ "$age" -lt 1800 ]  # 1800 seconds = 30 minutes
}

getprecipchance() {
	precipdata=$(echo "$weatherdata" | sed '16q;d' | grep -wo "[0-9]*%" 2>/dev/null)
	if [ -n "$precipdata" ]; then
		echo "$precipdata" | sort -rn 2>/dev/null | head -1
	else
		echo "0%"
	fi
}

getdailyhighlow() {
	tempdata=$(echo "$weatherdata" | sed '13q;d' | grep -o "m\\([-+]\\)*[0-9]\\+" 2>/dev/null | sed 's/[+m]//g')
	if [ -n "$tempdata" ]; then
		echo "$tempdata" | sort -g 2>/dev/null | sed -e 1b -e '$!d'
	else
		echo "??"
		echo "??"
	fi
}

readfile() { weatherdata="$(cat "$weatherreport")" ;}

validateweather() {
	[ -z "$weatherdata" ] && return 1
	# Check if we can extract valid temp data
	tempdata=$(echo "$weatherdata" | sed '13q;d' | grep -o "m\\([-+]\\)*[0-9]\\+" | sed 's/[+m]//g')
	[ -z "$tempdata" ] && return 1
	return 0
}

showweather() {
	readfile

	# If data invalid, try fetching new data
	if ! validateweather; then
		getforecast 2>/dev/null || exit 0
		readfile
		# Still invalid after fetch? Exit silently
		validateweather || exit 0
	fi

	precip=$(getprecipchance)
	highlow=$(getdailyhighlow)
	low=$(echo "$highlow" | head -1)
	high=$(echo "$highlow" | tail -1)

	printf "󰖐 %s 󰜗 %s° 󰖙 %s°\n" "$precip" "$low" "$high"
}

case $BLOCK_BUTTON in
	1) setsid -f "$TERMINAL" -e less -Sf "$weatherreport" ;;
	2) getforecast && showweather ;;
	3) notify-send "󰖐 Weather module" "\- Left click for full forecast.
- Middle click to update forecast.
󰖐: Chance of rain/snow
󰜗: Daily low
󰖙: Daily high" ;;
	6) setsid -f "$TERMINAL" -e "$EDITOR" "$0" ;;
esac

checkforecast || getforecast 2>/dev/null

showweather
