#!/usr/bin/env bash
# This script is sourced on build server, shebang is for convenience
# bash is used to have a predictable ulimit behavior
#
# @tags build

set -e
set -x

# remember the build directory
ROOT_DIR=$PWD

# concrete install location is configurable
if [ -z "${INSTALL_PATH}" ]; then
	INSTALL_PATH="/srv"
fi

# rotate backup of previous website
rm -rf ${INSTALL_PATH}/share/elektra/tool_data_backup
cp -ra ${INSTALL_PATH}/share/elektra/tool_data ${INSTALL_PATH}/share/elektra/tool_data_backup || /bin/true

# restore the previous page if something went wrong
restore() {
	rm -rf ${INSTALL_PATH}/share/elektra/tool_data
	mv ${INSTALL_PATH}/share/elektra/tool_data_backup ${INSTALL_PATH}/share/elektra/tool_data || /bin/true
}
trap restore EXIT INT QUIT TERM

# build the applications from scratch
rm -rf build && mkdir -p build && cd build

C_FLAGS='-D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fstack-protector-strong -Wstack-protector -fPIE -pie'
LD_FLAGS='-Wl,-z,now -Wl,-z,relro'

cmake -DENABLE_ASAN=ON -DBUILD_FULL=OFF -DBUILD_SHARED=ON -DBUILD_STATIC=OFF -DBUILD_DOCUMENTATION=OFF \
	-DCMAKE_INSTALL_PREFIX="${INSTALL_PATH}" \
	-DPLUGINS='ALL;-EXPERIMENTAL;-fstab;-ruby;-lua;-python;-xerces;-yamlcpp;file;-dbus' \
	-DTOOLS='kdb;website-backend;website-frontend' \
	-DCMAKE_C_FLAGS="$C_FLAGS" \
	-DCMAKE_CXX_FLAGS="$C_FLAGS" \
	-DCMAKE_EXE_LINKER_FLAGS="$LD_FLAGS" \
	..

make -j 3

# run tests (exclude tests which write in system paths)
make run_nokdbtests

# cleanup old installed libraries (might have plugin we do not want any more or cause problems)
rm -rf ${INSTALL_PATH}/lib/*

# if tests were ok, we can install
make install

# use installed binaries and libs
export PATH=${INSTALL_PATH}/bin:${PATH}
export LD_LIBRARY_PATH=${INSTALL_PATH}/lib:${INSTALL_PATH}/lib/elektra

# now lets first output some version information for the build log
kdb --version

# who executed this?
whoami

# print key database for debugging
kdb export /sw/elektra ni

# prevent jenkins from killing daemons
BUILD_ID=dontKillMe

# allow core dumps
ulimit -c unlimited

# place for core dumps (name by: echo "core_%t_%p" > /proc/sys/kernel/core_pattern)
cd ${INSTALL_PATH}

PID_FILE=$(kdb sget /sw/elektra/restbackend/#0/current/cppcms/daemon/lock /run/elektra-website-backend.pid)

ps -ef
printf "Old PID was: "
cat ${PID_FILE} || /bin/true
echo

IP=$(kdb sget /sw/elektra/restbackend/#0/current/cppcms/service/ip 127.0.0.1)
PORT=$(kdb sget /sw/elektra/restbackend/#0/current/cppcms/service/port 8080)

echo "The backend should running on $IP:$PORT"

netstat -tlpen

# then start the backend; succeed if it was not started before..
kdb stop-website-backend || /bin/true

# cleanup /tmp files from build
find /tmp -mindepth 1 -user $(id -u) -delete || true

# avoid 'address already in use'
while netstat -tlpen | grep "$IP:$PORT"; do
	sleep 1 # keep waiting (=downtime) short
done

# ensure daemon mode is enabled, otherwise script will be blocked
kdb set '/sw/elektra/restbackend/#0/current/cppcms/daemon/enable' '1'

# now start again
kdb run-website-backend || /bin/true

printf "New PID is: "
cat ${PID_FILE} || /bin/true
echo

netstat -tlpen

# and finally re-compile the frontend
# - the old frontend is still alive and does not get taken offline (not necessary)
# - the configuration script does also take care of deleting old files,
#   every configuration run will first clean the deployment directory and copy
#   required files afterwards, ensuring an always up-to-date deployment
kdb build-website-frontend

ELEKTRA_VERSION=$(kdb get --no-newline system/elektra/version/constants/KDB_VERSION)
API_DOC_DIR="${ROOT_DIR}/build/API_DOC/restapi/${ELEKTRA_VERSION}"

mkdir -p ${API_DOC_DIR}

# create and copy api description
apiary preview --path=$ROOT_DIR/doc/api_blueprints/snippet-sharing.apib --output=${API_DOC_DIR}/snippet-sharing.html
cp $ROOT_DIR/doc/api_blueprints/snippet-sharing.apib ${API_DOC_DIR}/snippet-sharing.apib
(
	cd ${API_DOC_DIR}/..
	rm -f current
	ln -s $ELEKTRA_VERSION current
)

ps -ef
ulimit -a
