#!/usr/bin/env bash

# Copyright 2008, 2009, 2010, 2011, 2012 Roland Olbricht
#
# This file is part of PT_Diagrams.
#
# PT_Diagrams is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# PT_Diagrams is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with PT_Diagrams.  If not, see <http://www.gnu.org/licenses/>.


ID=0
BBOX=
INFO=
DEBUG=
EXECBASE="`dirname $0`/../"

IFS=$'&'
for KEY_VAL in $QUERY_STRING; do
{
  if [[ ${KEY_VAL:0:3} == "id=" ]]; then
    ID="${KEY_VAL:3}"
  elif [[ ${KEY_VAL:0:5} == "bbox=" && ${KEY_VAL:0:9} != "bbox=-180" ]]; then
    BBOX=`echo "${KEY_VAL:5}" | $EXECBASE/bin/uncgi`
  elif [[ ${KEY_VAL:0:6} == "debug=" ]]; then
    DEBUG=`echo "${KEY_VAL:6}" | $EXECBASE/bin/uncgi`
  fi
}; done
unset IFS

EPOCHSECS=$(($ID * 60 + 1347432900))
SINCE=`date --utc --date="@$EPOCHSECS" '+%FT%H:%M:%SZ'`
UNTIL=`date --utc --date="@$(($EPOCHSECS + 60))" '+%FT%H:%M:%SZ'`

if [[ -z $BBOX ]]; then
  QUERY_STRING='data=[adiff:"'$SINCE'","'$UNTIL'"];(node(changed:"'$SINCE'","'$UNTIL'");way(changed:"'$SINCE'","'$UNTIL'");rel(changed:"'$SINCE'","'$UNTIL'"););out meta geom;'
else
  QUERY_STRING='data=[adiff:"'$SINCE'","'$UNTIL'"];(node(bbox)(changed:"'$SINCE'","'$UNTIL'");way(bbox)(changed:"'$SINCE'","'$UNTIL'");rel(bbox)(changed:"'$SINCE'","'$UNTIL'"););out meta geom;&bbox='$BBOX
fi
#REQUEST_METHOD=GET

if [[ -z $DEBUG ]]; then
  ./interpreter
else
  echo "Content-Type: text/plain"
  echo
  echo $QUERY_STRING
fi
