#!/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 $DATA_XML "http://api.worldweatheronline.com/free/v1/weather.ashx?q=${DATA_LOC}&format=xml&num_of_days=5&key=3d3a896d1e152006112211"
wget -q -O $DATA_XML "http://api.worldweatheronline.com/free/v1/weather.ashx?q=${DATA_LOC}&format=xml&num_of_days=5&key=f5ucz853vvmmqucxch8t3jvc"


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')

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

eXit 0
