#! /bin/sh

# параметры:
# $1 - поисковый запрос
# $2 - имя выходного xml-файл

cmd=`basename $0`
LOG=${cmd/get_/}.log
if [ ! -f $LOG ]; then LOG= ; fi
dt=`date "+%F %T"`

GEOC=`cat geocconf.ads 2> /dev/null`
if [ -z $GEOC ]; then
	GEOC=local-nm
fi
tmp_rq=$1
tmp_rq=${tmp_rq// /%20}
tmp_rq=${tmp_rq//\"/}
tmp_rq=`echo $tmp_rq | iconv -fcp866 -tutf8 -c`
tmp_fl=$2.tmp

if [ $GEOC = local-nm ]; then
	tmp_rq=`echo $tmp_rq | cut -d"&" -f1`
	wget -O $tmp_fl --timeout=2 --tries=2 "http://adishost/nominatim/search.php?q=$tmp_rq&format=xml" > /dev/null 2>&1
else
	wget -O $tmp_fl --timeout=2 --tries=2 "http://adishost/utils/get-map-coordinates.php?search=$tmp_rq&geocoder=$GEOC" > /dev/null 2>&1
fi
err=$?
if [ $LOG ]; then
	echo "=======" >> $LOG
	echo $GEOC: $tmp_rq >> $LOG
	xmllint -format $tmp_fl >> $LOG
	echo "$dt `date +%T` err=$err" >> $LOG
fi

iconv -c -futf8 -tcp866 $tmp_fl > $2 2>/dev/null
rm -f $tmp_fl
exit 0
