#!/usr/bin/env bash

# Copyright 2008, 2009, 2010, 2011, 2012 Roland Olbricht
#
# This file is part of Overpass_API.
#
# Overpass_API 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.
#
# Overpass_API 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 Overpass_API.  If not, see <http://www.gnu.org/licenses/>.

EXEC_DIR="`dirname $0`/"
if [[ ! ${EXEC_DIR:0:1} == "/" ]]; then
{
  EXEC_DIR="`pwd`/$EXEC_DIR"
};
fi

BIN_DIR="$EXEC_DIR/../bin"

OUTPUT_TYPE="xml"
BUF="`echo "$QUERY_STRING" | $BIN_DIR/uncgi`"
if [[ "${BUF:0:5}" == "debug" ]]; then
{
  DEBUG=yes
  echo "Content-Type: text/plain; charset=utf-8"
  echo
  BUF="${BUF:6}"
  echo "[$BUF]"
};
elif [[ "${BUF:0:3}" == "xml" ]]; then
{
  OTUPUT_TYPE="xml"
  BUF="${BUF:4}"
};
elif [[ "${BUF:0:5}" == "mapql" ]]; then
{
  OTUPUT_TYPE="mapql"
  BUF="${BUF:6}"
};
elif [[ "${BUF:0:7}" == "compact" ]]; then
{
  OTUPUT_TYPE="compact"
  BUF="${BUF:8}"
};
fi

# No mkdir - directory should be created and made world-writeable
# by the maintainer to allow periodic cleanups.
REQUEST_FILE=`mktemp /tmp/translate_xapi/XXXXXX`
$BIN_DIR/translate_xapi "${BUF}" >$REQUEST_FILE
EXITCODE=$?
if [[ $EXITCODE -ne 0 ]]; then
{
  echo "Content-Type: text/plain; charset=utf-8"
  echo
  echo "Error in [$BUF]:"
  cat <$REQUEST_FILE
};
else
{
  if [[ $DEBUG == "yes" ]]; then
  {
    cat <$REQUEST_FILE
    echo
  };
  fi
  REQUEST_METHOD=
  echo "Content-Type: text/plain; charset=utf-8"
  echo
  if [[ $OUTPUT_TYPE == "xml" ]]; then
  {
    echo "Your query in pretty XML:"
    echo
    ../bin/osm3s_query --dump-xml <$REQUEST_FILE
  };
  elif [[ $OUTPUT_TYPE == "mapql" ]]; then
  {
    echo "Your query in pretty OverpassQL:"
    echo
    ../bin/osm3s_query --dump-pretty-ql <$REQUEST_FILE
  };
  elif [[ $OUTPUT_TYPE == "compact" ]]; then
  {
    echo "Your query in compact OverpassQL:"
    echo
    ../bin/osm3s_query --dump-compact-ql <$REQUEST_FILE
    echo
  };
  fi
};
fi

rm $REQUEST_FILE
