#!/bin/sh
set -e
[ -n "$DEBUG" ] && set -x

# loc=$1
loc="Ottawa"
if [ -z "${loc}" ]; then
	loc="Ottawa"
fi

if [ -n "$REPORT" ]; then
	curl -s v2.wttr.in/"${loc}"?F | less
	exit 0
fi

data="$(curl -s wttr.in/"${loc}"?format=j1)"

class=
case "$(echo "${data}" | jq -r '.current_condition[].weatherCode')" in
113) class="sunny" ;;
116) class="partlycloudy" ;;
119) class="cloudy" ;;
122) class="verycloudy" ;;
143|248|260) class="fog" ;;
176|263|266|293|296|353) class="lightrain" ;;
179|182|185|281|284|311|314|317|350|362|365|374|377) class="hail" ;;
200|386|389|392) class="thunder" ;;
227|320) class="lightsnow" ;;
230|329|332|335|338|371|395) class="heavysnow" ;;
299|302|305|308|356|359) class="heavyrain" ;;
323|326|368) class="snowrain" ;;
esac

tooltip="$(curl -s v2.wttr.in/"${loc}"?ATFQ | tail -n5)"

# Print header
#printf "%-20s %-10s %-10s %-10s\n" "Description" "Temperature" "Class" "Tooltip"
#printf "%-20s %-10s %-10s %-10s\n" "------------" "-----------" "-----" "-------"

# Print weather data
echo "${data}" | jq --raw-output \
	--arg class "${class}" \
	--arg tooltip "$tooltip" \
	'.current_condition[] | 
	 { desc: .weatherDesc[0].value, temp: (.temp_C | tonumber), class: $class, tooltip: $tooltip } |
	 "\(.desc)\t\(.temp)\t\(.class)\t\(.tooltip)"' | \
	awk -F '\t' '{ printf "%-20s %-10s %-10s %-10s\n", $1, $2, $3, $4 }'

