#!/bin/sh

eXit() {
	echo .
	exit $1
} 

test -e /var/etc/.lcd-weather || eXit 1

DATA_DIR=/tmp/lcd
DATA_XML=/tmp/weather.xml

if [ -e /var/tuxbox/config/tuxwetter/tuxwetter.conf ]; then
	DATA_LOC=$(grep -m1 "Stadt=" /var/tuxbox/config/tuxwetter/tuxwetter.conf | cut -d= -f2 | cut -d, -f2,3)
fi
test -z $DATA_LOC && eXit 1

if [ -e /var/tuxbox/config/tuxwetter/tuxwetter.mcfg ]; then
	#MCFG_KEY=$(grep "^LicenseKey=" /var/tuxbox/config/tuxwetter/tuxwetter.mcfg | cut -d= -f2)
	MCFG_KEY="32z7znf5z7bwm2nednkyevb7"
fi
test -z $MCFG_KEY && eXit 1

test -d $DATA_DIR || mkdir -p $DATA_DIR

wget -q -O $DATA_XML "http://api.worldweatheronline.com/free/v1/weather.ashx?q=${DATA_LOC}&format=xml&num_of_days=2&key=${MCFG_KEY}"

if [ -e $DATA_XML ]; then

	query=$(sed -n 's/.*<query>\(.*\)<\/query>.*/\1\n/p' $DATA_XML)

	temp=$(sed -n 's/.*<temp_C>\(.*\)<\/temp_C>.*/\1\n/p'	$DATA_XML)

	tempmax=$(sed -e 's/<\/tempMaxC>/<\/tempMaxC>\n/g' $DATA_XML | \
			sed -n 's/.*<tempMaxC>\(.*\)<\/tempMaxC>.*/\1/p')

	iconurls=$(sed -e 's/<\/weatherIconUrl>/<\/weatherIconUrl>\n/g' $DATA_XML | \
			sed -n 's/.*<weatherIconUrl>\(.*\)<\/weatherIconUrl>.*/\1/p' | \
			sed -e 's/<!\[CDATA\[//g' -e 's/\]\]>//g')

	echo "$query"	 > $DATA_DIR/location
	echo "$temp"	 > $DATA_DIR/temperatures
	echo "$tempmax"	>> $DATA_DIR/temperatures

	rm -f $DATA_DIR/weathericons
	for url in $iconurls; do
		icon=${url##*/}
		echo ${icon:8:4}.png >> $DATA_DIR/weathericons
	done

	#TODO: fix lan/lon-entrys in $DATA_DIR/location
	#http://maps.google.com/maps/geo?output=xml&oe=utf8&ll=(LAT),(LON)&key=asdad&hl=de

	rm -f $DATA_XML
fi

eXit 0