#!/bin/bash

set -e

source /usr/bin/docker-entrypoint.sh

JOBARG=/usr/local/sbin/jobarg_server
JOBARRANGER_ETC_DIR=/etc/jobarranger
JAZ_CONFIG=${JOBARRANGER_ETC_DIR}/jobarg_server.conf
JAPIDFILE=${JAPIDFILE:-"/tmp/jobarg_server.pid"}
DBPORT=${DBPORT:-"3306"}
JAZDBPORT=${JAZDBPORT:-"3306"}

update_config_var $JAZ_CONFIG "DBType" "mysql"
update_config_var $JAZ_CONFIG "DBHost" "${ZBX_DB_SERVER_HOST}"
update_config_var $JAZ_CONFIG "DBName" "${MYSQL_ZBX_DATABASE}"
update_config_var $JAZ_CONFIG "DBUser" "${MYSQL_ZBX_DB_USER}"
update_config_var $JAZ_CONFIG "DBPassword" "${MYSQL_ZBX_DB_PASSWORD}"
update_config_var $JAZ_CONFIG "DBPort" "${DBPORT}"
update_config_var $JAZ_CONFIG "JazDBHost" "${JAZ_DB_SERVER_HOST}"
update_config_var $JAZ_CONFIG "JazDBName" "${MYSQL_JAZ_DATABASE}"
update_config_var $JAZ_CONFIG "JazDBUser" "${MYSQL_JAZ_DB_USER}"
update_config_var $JAZ_CONFIG "JazDBPassword" "${MYSQL_JAZ_DB_PASSWORD}"
update_config_var $JAZ_CONFIG "JazDBPort" "${JAZDBPORT}"
update_config_var $JAZ_CONFIG "JaPidFile" "${JAPIDFILE}"

check_db_connect_mysql() {
    local db_host="$1"
    local db_port="$2"
    local db_user="$3"
    local db_pass="$4"
    local db_name="$5"

    echo "********************"
    local WAIT_TIMEOUT=5
    local LOOP_MAX_CNT=20
    local LOOP_CNT=0

    until mysqladmin ping -h "${db_host}" -P "${db_port}" -u "${db_user}" -p"${db_pass}" --silent --connect-timeout=10 >/dev/null 2>&1; do
        echo "**** MySQL server at ${db_host}:${db_port} is not available. Waiting ${WAIT_TIMEOUT} seconds..."
        sleep "${WAIT_TIMEOUT}"
        LOOP_CNT=$((LOOP_CNT + 1))
        if [ "${LOOP_CNT}" -ge "${LOOP_MAX_CNT}" ]; then
            echo "*************** Cannot connect to DB at ${db_host}:${db_port} ******************"
            return 1
        fi
    done

    echo "**** MySQL server at ${db_host}:${db_port} is available for ${db_name}."
}


mysql_query() {
    query=$1
    local result=""

    result=$(mysql --silent --skip-column-names -h ${JAZ_DB_SERVER_HOST} -P ${JAZDBPORT:-3306} \
             -u ${MYSQL_JAZ_DB_USER} --password="${MYSQL_JAZ_DB_PASSWORD}" -e "$query")

    echo $result
}

### Check Database up or not ##### 
check_db_connect_mysql "$ZBX_DB_SERVER_HOST" "${DBPORT:-3306}" "$MYSQL_ZBX_DB_USER" "$MYSQL_ZBX_DB_PASSWORD" "$MYSQL_ZBX_DATABASE"
check_db_connect_mysql "$JAZ_DB_SERVER_HOST" "${JAZDBPORT:-3306}" "$MYSQL_JAZ_DB_USER" "$MYSQL_JAZ_DB_PASSWORD" "$MYSQL_JAZ_DATABASE"

##### Check Database exist or not only for JOBARRANGER #####
result=$(mysql_query "SELECT count(*) FROM information_schema.tables where TABLE_NAME like 'ja_2%'")
if [ "$result" = "0" ];then
    export LANG=C.UTF-8
    cat /usr/share/doc/jobarranger-server/database/mysql/MySQL_JA_CREATE_TABLE.sql | mysql --silent --skip-column-names -h ${JAZ_DB_SERVER_HOST} -P ${JAZDBPORT:-3306} -u${MYSQL_JAZ_DB_USER} -p"${MYSQL_JAZ_DB_PASSWORD}" ${MYSQL_JAZ_DATABASE} 1>/dev/null
    cat /usr/share/doc/jobarranger-server/database/data/JA_2_INSERT_TABLE.sql | mysql --silent --skip-column-names -h ${JAZ_DB_SERVER_HOST} -P ${JAZDBPORT:-3306} -u${MYSQL_JAZ_DB_USER} -p"${MYSQL_JAZ_DB_PASSWORD}" ${MYSQL_JAZ_DATABASE} 1>/dev/null
    echo "***********CREATE DATABASE***********"
else
    echo "*********There are [${result}] tables *******"
fi

# Remove stale PID file if exists
if [ -f "$JAPIDFILE" ]; then
    echo "Removing existing PID file at startup"
    rm -f "$JAPIDFILE"
fi

##### Jobarranger Server run #####
"$JOBARG" -fc "$JAZ_CONFIG"