#!/bin/bash

# TODO - error checking for osmosis, glosm-tiler
if [ "$#" -ne "2" ]; then
  echo "Script to generate map tiles with 3D buildings using glosm-tiler and OpenStreetMap data."
  echo "Usage: \"$0 X Y\""
  echo "       X, Y = tile identification on zoom 12"
  exit 1
fi

## begin - variables to change ##
# first commandline parameter X, second Y
tileX=$1
tileY=$2
tileZ=12
#min max generated tiles zoom
genZmin=14
genZmax=18

#XAPIaddress="http://open.mapquestapi.com/xapi/api/0.6/"
XAPIaddress="http://jxapi.openstreetmap.org/xapi/api/0.6/"

minlon=
maxlon=
minlat=
maxlat=

# where to store generated tiles (tmp folder is here too!!!)
tilesPath="/SET/YOUR/PATH/TO/TILES/"

# path to osmosis binary
osmosisPath="/PATH/TO/OSMOSIS/BINARY/osmosis" 
# path to glosm-tiler binary
tilerPath="/PATH/TO/GLOSM-TILER/BINARY/glosm-tiler"
## end - variables to change ##

# convert tiles XY to lon, lat
# math from http://almien.co.uk/OSM/Tools/Coord/source.php
deg2rad () {
  bc -l <<< "$1 * 0.0174532925"
}

rad2deg () {
  bc -l <<< "$1 * 57.2957795"
}

function tan () {
  bc -l <<< "s($1)/c($1)"
}

function sinh () {
  bc -l <<< "(e($1)-e(-$1))/2"
}

function MercToLat () {
  tmp=`sinh ${1}`
  tmp2=$(echo "a($tmp)" | bc -l)
  echo `rad2deg ${tmp2}`
}

tmp=$(echo "360/2^${tileZ}" | bc -l)
minlon=$(echo "-180+${tileX}*${tmp}" | bc -l)
maxlon=$(echo "${minlon}+${tmp}" | bc -l)

tmp=`deg2rad 85.0511`
tmp2=`tan ${tmp}`

LimitY=$(echo "l(${tmp2}+(1/c(${tmp})))" | bc -l)
RangeY=$(echo "2*${LimitY}" | bc -l)

tmp=$(echo "1/2^${tileZ}" | bc -l)
relY1=$(echo "${tileY}*${tmp}" | bc -l)
relY2=$(echo "${relY1}+${tmp}" | bc -l)

relY1=$(echo "${LimitY}-${RangeY}*${relY1}" | bc -l)
relY2=$(echo "${LimitY}-${RangeY}*${relY2}" | bc -l)

minlat="`MercToLat ${relY2}`"
maxlat="`MercToLat ${relY1}`"

# create temp directory
mkdir ${tilesPath}/tmp

# this reads osm data from XAPI
echo "Downloading tile data...\n"
# first download all building in tile
wget --header="accept-encoding: gzip" ${XAPIaddress}way[building=*][bbox=${minlon},${minlat},${maxlon},${maxlat}] -O ${tilesPath}/tmp/out_${tileX}_${tileY}.osm.gz
if [ "$?" -ne "0" ]; then
  echo -e '\a\e[1;31m'"ERROR:"'\e[0m'" XAPI data download failed!"
  exit 2
fi
# strip everythink except ways with tag building:levels and height 
${osmosisPath} --read-xml enableDateParsing=no file="${tilesPath}tmp/out_${tileX}_${tileY}.osm.gz" --way-key keyList=building:levels,height --used-node --write-xml file=${tilesPath}tmp/out_${tileX}_${tileY}-building.osm

# generate tiles
${tilerPath} -z ${genZmin} -Z ${genZmax} -x ${minlon} -X ${maxlon} -y ${minlat} -Y ${maxlat} ${tilesPath}tmp/out_${tileX}_${tileY}-building.osm ${tilesPath}

# clean up
rm -f ${tilesPath}tmp/out_${tileX}_${tileY}*
