#!/bin/bash
#############################
# This is used to configure the behavior of the various bootstrap scripts.
#############################

# Prevent double inclusion (so vars can be modifed after first include)
if [ -n "${WORKING_DIR}" ]; then
	return
fi

IMPORT_DATA_GEOSERVER=false
IMPORT_DATA_NEO4J_SPATIAL=false
IMPORT_DATA_POSTGIS=true
IMPORT_DATA_SPATIALITE=true

# Comma separated list of srids for which datasets will be generated
# This is useful when creating multiple datasets (when creating/updating data from scratch)
# Note that only the last SRID in the list will be kept in the database, all the others will be overwritten
#TARGET_SRID="3857,4326"
TARGET_SRID="4326"
UPDATE_DATA=false
USE_3D=true

CACHE_DIR_LOCAL="/tmp/vagrant-cache"
CACHE_DIR_REMOTE="https://dbis-owncloud.uibk.ac.at/index.php/s/kgjm3CItQJ6P374/download?path=%2F2016&files="
DEPLOY_DIR="/opt"
DATA_DIR="$DEPLOY_DIR/data"
SETUP_DIR="/setup"
USE_COLOR=true
USE_TIMINGS=false
VERBOSE=false
WORKING_DIR="/var/log/vagrant_bootstrap"

# Parameters that can also (some must) be passed as arguments
DEPLOY_ALL_DATASETS=false
IS_JENKINS_DEPLOY=false
IS_LOCAL_DEPLOY=false
PG_DB_NAME="isochrone"
PG_DB_USER="@db_username@"
PG_DB_PASSWORD="@db_password@"
TOMCAT_PASSWORD="@tomcat_password@"

############################
# Calculated variables
############################

# Do not change anything below this line!

EXEC_JAVA=java
EXEC_PGDUMP=pg_dump
EXEC_PSQL=psql
EXEC_WGET=wget
POSTGRES_SHARE="$(dirname /usr/pgsql*/.)""/share"
if [ ! -d ${POSTGRES_SHARE} ]; then
	POSTGRES_SHARE="/usr/share/pgsql"
fi

AVAILABLE_GDAL=$([ -d "${DEPLOY_DIR}/gdal" ] && echo true || echo false)
AVAILABLE_GEOSERVER=$([ -d "${DEPLOY_DIR}/geoserver" ] && echo true || echo false)
AVAILABLE_ISOCHRONE_DATAMODEL=$([ -d "${DEPLOY_DIR}/isochrone-datamodel" ] && echo true || echo false)
AVAILABLE_ISOCHRONE_TOOLS=$([ -f "${DEPLOY_DIR}/isochrone-tools.jar" ] && echo true || echo false)
AVAILABLE_NEO4J=$([ -d "${DEPLOY_DIR}/neo4j" ] && echo true || echo false)
AVAILABLE_NEO4J_SPATIAL=$([ -d "${DEPLOY_DIR}/neo4j-spatial" ] && echo true || echo false)
AVAILABLE_POSTGRES=$(type ${EXEC_PSQL} >/dev/null 2>&1 && echo true || echo false)
AVAILABLE_POSTGIS=$([ -f "${POSTGRES_SHARE}/extension/postgis.control" ] && echo true || echo false)
AVAILABLE_SPATIALITE_ADMIN=$([ -f "${DEPLOY_DIR}/phpliteadmin/phpliteadmin.config.php" ] && echo true || echo false)

DOWNLOAD_DIR="${CACHE_DIR_LOCAL}/wget"
if [ ! -f "${SETUP_DIR}" ]; then
	SCRIPT="$(readlink -f ${BASH_SOURCE[0]})"
	SCRIPT_DIR="$(dirname ${SCRIPT})"
	SETUP_DIR="$(dirname ${SCRIPT_DIR})"
fi
SHARED_CONF_DIR="${SETUP_DIR}/conf"
SHARED_IMG_DIR="${SETUP_DIR}/img"

# Function definitions

function fn_arg2boolean() {
	local OUTVAR="${1}"
	local ARG="${2}"
	local VALUE="${3}" # Default value

	if [ -n "$ARG" ]; then
		if [ "$ARG" == "true" ]; then
			VALUE=true
		else
			VALUE=false
		fi
	fi

	eval $OUTVAR="\$VALUE"
}

function fn_arg2string() {
	local OUTVAR="${1}"
	local ARG="${2}"
	local VALUE="${3}" # Default value

	if [ "${VALUE:0:1}" == "@" ]; then
			VALUE="${ARG}"
	fi
	if [ "${VALUE:0:1}" == "@" ]; then
		fn_echo "No (or invalid) database user supplied!" "ERROR"
		exit 1
	fi

	eval $OUTVAR="\$VALUE"
}

function fn_check_status {
	local status="$?"

	if [ $status -ne 0 ]; then
		local message="${1}"
		if [ -z "${1}" ]; then
    		message="An error occurred. The process will exit now with status $status"
		fi

		fn_echo "${message}" "ERROR"
		exit $status
	fi
}

function fn_download() {
	local FILE="${1}"
	local URL="${2}"
	local ARGS="${3} --continue --no-check-certificate --quiet"
	local FAIL_ON_ERROR="${4}"
	if [ -z "$FAIL_ON_ERROR" ]; then
		FAIL_ON_ERROR=true
	fi

	fn_echo "  - downloading ${FILE}" "DEBUG"
	fn_echo "  - from URL: ${URL}" "DEBUG"
	fn_echo "  - with wget arguments: ${ARGS}" "DEBUG"

#	${EXEC_WGET} ${ARGS} --spider "${URL}"
#	fn_check_status "  - download canceled, since nothing was found at URL \"${URL}\""

	${EXEC_WGET} ${ARGS} --output-document="${FILE}" "${URL}"
	if $FAIL_ON_ERROR; then
		fn_check_status "  - download failed for URL \"${URL}\""
	fi

	return $?
}

function fn_download_newer() {
	local FILE="${1}"
	local URL="${2}"
	local ARGS="${3} --timestamping"
	local FAIL_ON_ERROR="${4}"
	if [ -z "$FAIL_ON_ERROR" ]; then
		FAIL_ON_ERROR=true
	fi

	if [ -f "${1}" ]; then
		fn_echo "  - not downloading ${1}, since it already exists" "DEBUG"
		return 0
	fi

	fn_download "${FILE}" "${URL}" "${ARGS}" "${FAIL_ON_ERROR}"
	return $?
}

function fn_echo() {
	local MESSAGE="${1}"
	local LEVEL="${2}"
	local COLOR="\e[93m" # default color is light green
	local DEFAULT_COLOR="\e[39m"

	if ${USE_TIMINGS}; then
		TIME=$(date +"%T.%N")
		MESSAGE="[${TIME}] ${MESSAGE}"
	fi

	if ${USE_COLOR} ; then
		case "${LEVEL,,}" in
			"debug") COLOR="\e[34m" ;;	# Blue
			"error") COLOR="\e[91m" ;;	# Light red
			"warn")  COLOR="\e[93m" ;;	# light yellow
			*) 		 COLOR="\e[92m" ;;	# light green (on level=info, no level set or invalid level given)
		esac

		if [ "${LEVEL,,}" = "debug" ] && ! ${VERBOSE}; then
			return 0
		fi

		echo -e "${COLOR}${MESSAGE}${DEFAULT_COLOR}"
	else
		echo "${MESSAGE}"
	fi
}

function fn_service_start() {
	local SERVICE_NAME="$1"

	fn_echo "Starting service \"${SERVICE_NAME}\"" "DEBUG"
	touch "service_start_$SERVICE_NAME.log" 2>&1
	if [ "$DISTRI_TYPE" == "CentOS 6" ]; then
		service $SERVICE_NAME start >> "service_start_$SERVICE_NAME.log" 2>&1
		chkconfig $SERVICE_NAME on "service_start_$SERVICE_NAME.log" 2>&1
	else
		systemctl start $SERVICE_NAME >> "service_start_$SERVICE_NAME.log" 2>&1
		systemctl enable $SERVICE_NAME >> "service_start_$SERVICE_NAME.log" 2>&1
	fi

	sleep 2
}

function fn_service_stop() {
	local SERVICE_NAME="$1"

	fn_echo "Stopping service \"${SERVICE_NAME}\"" "DEBUG"
	touch "service_stop_$SERVICE_NAME.log" 2>&1
	if [ "$DISTRI_TYPE" == "CentOS 6" ]; then
		service $SERVICE_NAME stop >> "service_stop_$SERVICE_NAME.log" 2>&1
		chkconfig $SERVICE_NAME off "service_stop_$SERVICE_NAME.log" 2>&1
	else
		systemctl stop $SERVICE_NAME >> "service_stop_$SERVICE_NAME.log" 2>&1
		systemctl disable $SERVICE_NAME >> "service_stop_$SERVICE_NAME.log" 2>&1
	fi

	sleep 2
}

