#!/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
echo "all arguments: "$@
echo "0: "$0
echo "1: "$1

source /ox-installer/lib/common.bash

# The interactive bash environment is for debugging and config evaluation ... 
# Enter by:
# $ docker run -it --rm gitlab.open-xchange.com:4567/docker/open-xchange-docker/<image-name>:<tag> bash
# e.g.
# $ docker run -it --rm gitlab.open-xchange.com:4567/docker/open-xchange-docker/release-7-10-1/open-xchange-groupware:release-7.10.1 bash
if [[ "$1" == "bash" ]]; then
    echo "Starting interactive shell (unconfigured container environment)..."
    bash
    echo "Interactive shell stopped."
    exit 0;
fi

echo "Checking container config..."
if [ ! -f /opt/open-xchange/etc/configdb.properties ]; then
    echo "... Container config not found, copying default config from /opt/open-xchange/etc.dist/"
    cp -R /opt/open-xchange/etc.dist/* /opt/open-xchange/etc/
    chown -R open-xchange:open-xchange /opt/open-xchange/etc

fi

# TODO: 
if [[ "$1" == "supervisord" ]]; then
    echo "Starting supervisord services ..."
    ls -lah /etc/supervisor/conf.d/
    supervisord -c /etc/supervisor/supervisord.conf
    # wait for services to be available ...
    sleep 10

    /ox-installer/config/init-middleware.sh

fi

# # Tailing OX Logs as container output
touch /var/log/open-xchange/open-xchange.log.0

chown -R open-xchange:open-xchange /var/log/open-xchange
tail -F /var/log/open-xchange/open-xchange.log.0

# Moved the touch/tail into its own script. This can be overriden by any child-container but will still ensure that the image will work ...
#/opt/open-xchange/docker/tail-ox-logs.sh
