#!/bin/bash
#
# Copyright (C) 2019 OX Software GmbH
# 
# This file is part of OX Automation.
#
# OX Automation is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OX Automation is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# 
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with OX Automation. If not, see <http://www.gnu.org/licenses/>.
#
#
# Authors:
# Benedikt Kroening <benedikt.kroening@open-xchange.com>
#
set -e
SCRIPT_DIR="$( cd "$(dirname "$0")" ; pwd -P)"

source ${SCRIPT_DIR}/../../lib/common.bash

INIT_STATE_FILE="/opt/open-xchange/etc/01-init-node-done"

if [ ! -f ${INIT_STATE_FILE} ]; then

    echo "Configuring backend..."
    # setting default config (key, value, filepath)
    setOXProperty com.openexchange.sessiond.autologin true /opt/open-xchange/etc/sessiond.properties
    setOXProperty com.openexchange.IPCheck false /opt/open-xchange/etc/server.properties
    setOXProperty com.openexchange.dispatcher.prefix "/appsuite/api/" /opt/open-xchange/etc/server.properties

    if [ "${OX_HAZELCAST_ENABLED}" = true ]; then
        # enable cluster functionality
        echo "Enabling Hazelcast Cluster ..."
        setOXProperty com.openexchange.hazelcast.enabled true /opt/open-xchange/etc/hazelcast.properties
        setOXProperty com.openexchange.hazelcast.network.join multicast /opt/open-xchange/etc/hazelcast.properties
        setOXProperty com.openexchange.hazelcast.network.interfaces "" /opt/open-xchange/etc/hazelcast.properties
        setOXProperty com.openexchange.hazelcast.configuration.map.asyncBackupCount 1 /opt/open-xchange/etc/hazelcast.properties
    else
        echo "Disabling Hazelcast Cluster ..."
        setOXProperty com.openexchange.hazelcast.enabled false /opt/open-xchange/etc/hazelcast.properties
    fi

    echo "Waiting for database service ..."
    waitPort ${DATABASE_HOST_NAME} ${DATABASE_HOST_PORT}

    # Adding check if the configdb already exists - if not we will have to provide the "-i" flag to initconfigdb script.
    # This is required since the script wont create the admin with allowence from remote hosts even tough the flag is specified. 
    # Simple workaround is to check if the DB exists - if yes we will NOT provide the -i flag as it would overwrite the DB.
    # (grep -ow will only output the exact string "configdb" if found)
    RESULT=`mysqlshow -h${DATABASE_HOST_NAME}  -P ${DATABASE_HOST_PORT} --user=${OX_CONFIGDB_USER} --password=${OX_CONFIGDB_PASS} ${OX_CONFIGDB_NAME} | grep -ow configdb`
    if [ "$RESULT" != "configdb" ]; then
        echo "Bootstrapping the configdb ..."
        sleep 5
        BOOTSTRAP_CONFIGDB="-i"
    fi

    echo "Running initconfigdb script with provided environment variables (Host: ${DATABASE_HOST_NAME}) ... "
    /opt/open-xchange/sbin/initconfigdb --configdb-host "${DATABASE_HOST_NAME}" \
            --configdb-port "${DATABASE_HOST_PORT}" \
            --mysql-root-user "${DATABASE_ROOT_USER}" \
            --mysql-root-passwd "${DATABASE_ROOT_PASS}" \
            --configdb-user "${OX_CONFIGDB_USER}" \
            --configdb-pass "${OX_CONFIGDB_PASS}"  \
            --configdb-dbname "${OX_CONFIGDB_NAME}" \
            -a ${BOOTSTRAP_CONFIGDB}

    # Replacing OX_ROUTE with $(hostname)
    
    if [[ "${INSTALL_TYPE}" == "singlenode" ]]; then
        echo "Using singlenode as route name ..."
        export OX_ROUTE=singlenode
    else
        echo "Using actual hostname as route name ..."
        export OX_ROUTE=$(hostname)
    fi
    echo "WARNING: overriding OX_ROUTE variable with "$OX_ROUTE

    echo "Running oxinstaller for ox server ${OX_SERVER_NAME} with route ${OX_ROUTE}"
    /opt/open-xchange/sbin/oxinstaller \
            --servername          "${OX_SERVER_NAME}" \
            --imapserver          "${OX_MAIL_HOST}" \
            --smtpserver          "${OX_MAIL_HOST}" \
            --configdb-readhost   "${DATABASE_HOST_NAME}" \
            --configdb-readport   "${DATABASE_HOST_PORT}" \
            --configdb-writehost  "${DATABASE_HOST_NAME}" \
            --configdb-writeport  "${DATABASE_HOST_PORT}" \
            --configdb-user       "${OX_CONFIGDB_USER}" \
            --configdb-pass       "${OX_CONFIGDB_PASS}" \
            --configdb-dbname     "${OX_CONFIGDB_NAME}" \
            --master-user         "${OX_ADMINMASTER_USER}" \
            --master-pass         "${OX_ADMINMASTER_PASS}" \
            --jkroute             "${OX_ROUTE}" \
            --name-of-oxcluster   "${OX_CLUSTER_NAME}" \
            --no-license \
            --servermemory 1024 \
            --network-listener-host "*" \


    echo "$(date)" > ${INIT_STATE_FILE}
    
else
    echo "WARNING: This scripts has already been executed and will be skipped!"
    sleep 5
fi

# echo "Init node finishe"
#cat ${INIT_STATE_FILE}
