#!/bin/sh

eXit() {
	echo .
	exit $1
}

#test -e /var/etc/.lcd-weather || eXit 1
test -e /tmp/.lcd4linux || 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
test -d $DATA_DIR || mkdir -p $DATA_DIR

wget -q -O /tmp/weathertemp.xml "http://api.worldweatheronline.com/premium/v1/weather.ashx?key=b4ffdsdf173d095ee4fs415581f193132170108&q=50.14,9.16&num_of_days=5&tp=3&format=xml"

sed -i 's/<\/[^>]*>/&\n/g' /tmp/weathertemp.xml

cp -f /tmp/weathertemp.xml $DATA_XML

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/<\/maxtempC>/<\/maxtempC>\n/g' $DATA_XML | sed -n 's/.*<maxtempC>\(.*\)<\/maxtempC>.*/\1/p')

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

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

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

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

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

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

	date=$(sed -e 's/<\/date>/<\/date>\n/g' $DATA_XML | \
			sed -n 's/.*<date>\(.*\)<\/date>.*/\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')

	rm -f $DATA_DIR/weather_*

	echo "$query"		 > $DATA_DIR/weather_location
	echo "$temp"		 > $DATA_DIR/weather_temperatures_akt
	echo "$tempmax"		>> $DATA_DIR/weather_temperatures_max
	echo "$tempmin"		>> $DATA_DIR/weather_temperatures_min
	echo "$messzeit"	 > $DATA_DIR/weather_time
	echo "$windkmh"		 > $DATA_DIR/weather_windkmh
	echo "$winddir"		 > $DATA_DIR/weather_winddir
	echo "$feuchte"		 > $DATA_DIR/weather_luftfeuchte
	echo "$druck"		 > $DATA_DIR/weather_luftdruck
	echo "$date"		 > $DATA_DIR/weather_dates

	for url in $iconurls; do
		icon=${url##*/}
		echo ${icon:8:4}.png >> $DATA_DIR/weather_icons
	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
	rm -f /tmp/weathertemp
fi

eXit 0
