#!/usr/bin/sh

ERROR="[ !! ]"
WARNING="[ ** ]"
OK="[ ok ]"

# Check if we got everything we need

check_binary()
{
	which $1 > /dev/null 2>&1
	if test $? = 1 ; then
		echo "${ERROR} Could not find $1. $2"
		exit 1
	fi
}

if test "x$CXX" = "x" ; then
	CXX="g++"
fi
if test "x$CXX" = "x" ; then
	CXX=g++
fi

check_binary ${CXX} "What happened to your compiler?"

if test -z "$1"; then
	echo "${WARNING} USAGE: $0 <file.cpp> [file.cpp ... ]"
	exit 1
fi

CXXFLAGS=" -O2 -flto=auto -ffat-lto-objects -fexceptions -g -grecord-gcc-switches -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -fstack-protector-strong -specs=/usr/lib/rpm/redhat/redhat-annobin-cc1  -m64 -march=x86-64-v2 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection  -O2 -Wall -W -Wno-unused-parameter -Woverloaded-virtual -Wshadow    -fvisibility=hidden -fPIC -include znc/zncconfig.h -I/usr/include $CXXFLAGS"
LIBS="-lssl -lcrypto  -lz -licuuc -licudata  $LIBS"
MODLINK="-shared $MODLINK"
VERSION="1.8.2"

# Ugly cygwin stuff :(
if test -n ""; then
	prefix="/usr"
	exec_prefix="/usr"
	LDFLAGS="-L/usr/lib64 $LDFLAGS"
	LIBS="-lznc $LIBS"
fi

while test -n "$1"
do
	FILE=$1
	shift

	MOD="${FILE%.cpp}"
	MOD="${MOD%.cc}"
	MOD="${MOD##*/}"

	if test ! -f "${FILE}"; then
		echo "${ERROR} Building \"${MOD}\" for ZNC $VERSION... File not found"
		exit 1
	else
		printf "Building \"${MOD}.so\" for ZNC $VERSION... "
		if ${CXX} ${CXXFLAGS} ${INCLUDES} ${LDFLAGS} ${MODLINK} -o "${MOD}.so" "${FILE}" ${LIBS} ; then
			echo "${OK}"
		else
			echo "${ERROR} Error while building \"${MOD}.so\""
			exit 1
		fi
	fi
done

exit 0
