#!/bin/sh
usage="$0 location"

test $# -eq 0 && echo "$usage" && exit 1

loc=`echo $@ | sed 's/ /+/g'`
resp=`curl 'http://www.wunderground.com/cgi-bin/findweather/hdfForecast?query='$loc`

# build actual json url
key=`echo "$resp" | awk '/\tk:/ {print $2}' | sed "s/[',]//g"`
locationcode=`echo "$resp" | awk '/\tzmw:/ {print $2}' | sed "s/[',]//g"`
json=`curl "http://api-ak.wunderground.com/api/${key}/forecast10day/hourly10day/labels/astronomy10day/lang:EN/units:metric/v:2.0/bestfct:1/q/zmw:${locationcode}.json"`

usefuljson=`echo "$json" | jq '.forecast|.days|.[]|.hours|.[]|{epoch:.date.epoch, temperature, pop, snow, humidity, condition}'`

echo "$json" | jq -r '.current_observation.station|.id,.name,.city'

echo "$usefuljson" | sed 's/"//g; s/,//g; s/: /:/' | while read line; do
	test "$line" = "}" && printf '\n' && continue
	test "$line" = "{" && continue

	epoch=`echo "$line" | awk -F : '($1 == "epoch") {print $2}'`
	if test "$epoch" != "" && test "$epoch" != "null"; then
		datestr=`printf "@%s" "$epoch"`
		date=`date --date=$datestr +'%a %d, %R'`
		oldcurday="$curday"
		curday=`echo "$date" | awk '{print $1}'`
		test "$curday" != "$oldcurday" && printf '\n'
		printf "%s - " "$date"
		epoch=""
	fi

	echo "$line" | awk -F : '{
		if ($1 == "temperature") { printf("%-4.1f°C, ", $2) }
		if ($1 == "pop") { printf("%2.0f%% rain, ", $2) }
		if ($1 == "snow" && $2 > 0) { printf("%2.0f%% snow, ", $2) }
		if ($1 == "humidity") { printf("%2.0f%% humidity, ", $2) }
		if ($1 == "condition") { printf("%s", $2) }
	}'
done

