#!/usr/bin/env bash
#
# Zephir Parser
#
# Copyright (c) 2013-2017 Zephir Team and contributors
#
# This source file is subject the MIT license, that is bundled with
# this package in the file LICENSE, and is available through the
# world-wide-web at the following url:
# http://zephir-lang.com/license.html
#
# If you did not receive a copy of the MIT license and are unable
# to obtain it through the world-wide-web, please send a note to
# license@zephir-lang.com so we can mail you a copy immediately.

CC=${CC:-}

PHPIZE_BIN=$(phpenv which phpize)
PHP_CONFIG_BIN=$(phpenv which php-config)
GCC_BIN=${GCC_BIN:-$(command -v gcc 2>/dev/null)}
CLANG_BIN=${CLANG_BIN:-$(command -v clang 2>/dev/null)}

RE2C_BIN=${RE2C_BIN:-$(command -v re2c 2>/dev/null)}

if [ x"$CC" = x ]; then
	echo -e "error: unable to locate the compiler"
	exit 1
fi

if [ x"$RE2C_BIN" = x ]; then
  echo -e "error: unable to locate the re2c"
  exit 2
fi

cd ${TRAVIS_BUILD_DIR}/parser

rm -f *.o *.lo

${CC} --version

${RE2C_BIN} -o scanner.c scanner.re

# Compile lemon
if [ ! -f lemon ]; then
	${CC} lemon.c -o lemon
fi

echo -e "Generating PHP 5 parser..."
./lemon -s parser.php5.lemon
if [ ! -f parser.php5.c ]; then
	echo "error: couldn't generate parser"
	exit 2
fi
echo

./lemon -s parser.php7.lemon
if [ ! -f parser.php7.c ]; then
	echo "error: couldn't generate parser"
	exit 2
fi
echo

echo "#include <php.h>" > parser.c
echo "#if PHP_VERSION_ID < 70000" >> parser.c
cat parser.php5.c >> parser.c
echo "#else" >> parser.c
cat parser.php7.c >> parser.c
echo "#endif" >> parser.c
cat base.c >> parser.c

sed s/"\#line"/"\/\/"/g scanner.c > xx && mv -f xx scanner.c
sed s/"#line"/"\/\/"/g parser.c > xx && mv -f xx parser.c

# Move to specified architecture
cd ${TRAVIS_BUILD_DIR}

# Clean current compilation
if [ -f Makefile ]; then
	make clean
	${PHPIZE_BIN} --clean
fi

# Perform the compilation
${PHPIZE_BIN}
./configure --with-php-config=${PHP_CONFIG_BIN} --enable-zephir_parser
make -j"$(getconf _NPROCESSORS_ONLN)"
make test
make install

phpenv config-add ${TRAVIS_BUILD_DIR}/tests/ci/zephir_parser.ini

echo -e "\nThanks for compiling Zephir Parser!\nBuild succeed: Please restart your web server to complete the installation"
