#!/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" "maria"
update_config_var $JAZ_CONFIG "DBHost" "${ZBX_DB_SERVER_HOST}"
update_config_var $JAZ_CONFIG "DBName" "${MARIA_ZBX_DATABASE}"
update_config_var $JAZ_CONFIG "DBUser" "${MARIA_ZBX_DB_USER}"
update_config_var $JAZ_CONFIG "DBPassword" "${MARIA_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" "${MARIA_JAZ_DATABASE}"
update_config_var $JAZ_CONFIG "JazDBUser" "${MARIA_JAZ_DB_USER}"
update_config_var $JAZ_CONFIG "JazDBPassword" "${MARIA_JAZ_DB_PASSWORD}"
update_config_var $JAZ_CONFIG "JazDBPort" "${JAZDBPORT}"
update_config_var $JAZ_CONFIG "JaPidFile" "${JAPIDFILE}"

check_db_connect_maria() {
    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 mariadb --ssl=0 \
          -h "${db_host}" \
          -P "${db_port}" \
          -u "${db_user}" \
          -p"${db_pass}" \
          -e "SELECT 1;" >/dev/null 2>&1
    do
        echo "**** Maria 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 "**** Maria server at ${db_host}:${db_port} is available for ${db_name}."
}

maria_query() {
    local query="$1"
    mariadb --silent --skip-column-names -h "${ZBX_DB_SERVER_HOST}" -P "${JAZDBPORT:-3306}" -u "${MARIA_JAZ_DB_USER}" -p"${MARIA_JAZ_DB_PASSWORD}" -e "$query"
}

### Check Database up or not ##### 
check_db_connect_maria "$ZBX_DB_SERVER_HOST" "${DBPORT:-3306}" "$MARIA_ZBX_DB_USER" "$MARIA_ZBX_DB_PASSWORD" "$MARIA_ZBX_DATABASE"
check_db_connect_maria "$JAZ_DB_SERVER_HOST" "${JAZDBPORT:-3306}" "$MARIA_JAZ_DB_USER" "$MARIA_JAZ_DB_PASSWORD" "$MARIA_JAZ_DATABASE"

##### Check Database exist or not only for JOBARRANGER #####
result=$(maria_query "SELECT count(*) FROM information_schema.tables where TABLE_NAME like 'ja_2%'")
set -o pipefail

if [ "${result:-0}" -eq 0 ]; then
    export LANG=C.UTF-8
    echo "**** No tables found. Creating tables..."

    if ! mariadb --silent --skip-column-names -h "${JAZ_DB_SERVER_HOST}" -P "${JAZDBPORT:-3306}" -u"${MARIA_JAZ_DB_USER}" -p"${MARIA_JAZ_DB_PASSWORD}" "${MARIA_JAZ_DATABASE}" < /usr/share/doc/jobarranger-server/database/mysql/MySQL_JA_CREATE_TABLE.sql; then
        echo "ERROR: Failed to create tables" >&2
        exit 1
    fi

    if ! mariadb --silent --skip-column-names -h "${JAZ_DB_SERVER_HOST}" -P "${JAZDBPORT:-3306}" -u"${MARIA_JAZ_DB_USER}" -p"${MARIA_JAZ_DB_PASSWORD}" "${MARIA_JAZ_DATABASE}" < /usr/share/doc/jobarranger-server/database/data/JA_2_INSERT_TABLE.sql; then
        echo "ERROR: Failed to insert initial data" >&2
        exit 1
    fi

    echo "*********** CREATE DATABASE SUCCESS ***********"

else
    echo "**** Tables already exist: [${result}]"

    # Validation query to ensure DB is actually usable
    if ! mariadb --silent --skip-column-names -h "${JAZ_DB_SERVER_HOST}" -P "${JAZDBPORT:-3306}" -u"${MARIA_JAZ_DB_USER}" -p"${MARIA_JAZ_DB_PASSWORD}" "${MARIA_JAZ_DATABASE}" -e "SELECT 1;" >/dev/null; then
        echo "ERROR: Database exists but connection or permissions failed" >&2
        exit 1
    fi

    echo "**** Database validation successful ****"
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"
