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

set -e

# Ensure that this is being run inside a CI container
#if [ "${CI}" != "true" ]; then
    #echo "This script is designed to run inside a CI container only. Exiting"
    #exit 1
#fi

CURRENT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )

CC=${CC:-gcc}

PHPIZE_BIN=$(phpenv which phpize)
PHP_CONFIG_BIN=$(phpenv which php-config)

GCC_BIN=$(command -v $CC 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 1
fi

cd ${CURRENT_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

PHP_FULL_VERSION=`${PHP_CONFIG_BIN} --version`

if [ $? != 0 ]; then
	echo "php-config is not installed"
	exit 1
fi

if [ "${PHP_FULL_VERSION:0:3}" == "5.3" ]; then
	echo "php 5.3 is no longer supported"
	exit 1
fi

if [ "${PHP_FULL_VERSION:0:3}" == "5.4" ]; then
	echo "php 5.4 is no longer supported"
	exit 1
fi

if [ "${PHP_FULL_VERSION:0:1}" == "5" ]; then
	PHP_VERSION="php5"
else
	PHP_VERSION="php7"
fi

echo -e "Generating parser [parser.${PHP_VERSION}.lemon]..."
./lemon -s parser.${PHP_VERSION}.lemon

if [ ! -f parser.${PHP_VERSION}.c ]; then
	echo "error: couldn't generate parser"
	exit 1
fi

echo "#include <php.h>" > parser.c
cat parser.${PHP_VERSION}.c >> 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

cd ${CURRENT_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 ${CURRENT_DIR}/zephir_parser.ini

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