#!/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"

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]"
};
fi

# No mkdir - directory should be created and made world-writeable
# by the maintainer to allow periodic cleanups.
XML_REQUEST="`$BIN_DIR/translate_xapi --force-meta \"${BUF}\"`"
EXITCODE=$?
if [[ $EXITCODE -ne 0 ]]; then
{
  echo "Content-Type: text/plain; charset=utf-8"
  echo "Status: 400 Bad Request"
  echo
  echo "Error in [$BUF]:"
  echo "$XML_REQUEST"
};
else
{
  if [[ $DEBUG == "yes" ]]; then
  {
    echo "$XML_REQUEST"
    echo
  };
  fi
  REQUEST_METHOD=
  echo "$XML_REQUEST" | ./interpreter
};
fi
