#!/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:-"5432"}
JAZDBPORT=${JAZDBPORT:-"5432"}

update_config_var $JAZ_CONFIG "DBType" "postgres"
update_config_var $JAZ_CONFIG "DBHost" "${ZBX_DB_SERVER_HOST}"
update_config_var $JAZ_CONFIG "DBName" "${POSTGRES_ZBX_DATABASE}"
update_config_var $JAZ_CONFIG "DBUser" "${POSTGRES_ZBX_DB_USER}"
update_config_var $JAZ_CONFIG "DBPassword" "${POSTGRES_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" "${POSTGRES_JAZ_DATABASE}"
update_config_var $JAZ_CONFIG "JazDBUser" "${POSTGRES_JAZ_DB_USER}"
update_config_var $JAZ_CONFIG "JazDBPassword" "${POSTGRES_JAZ_DB_PASSWORD}"
update_config_var $JAZ_CONFIG "JazDBPort" "${JAZDBPORT}"
update_config_var $JAZ_CONFIG "JaPidFile" "${JAPIDFILE}"

check_db_connect_postgres() {
    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

    export PGPASSWORD="$db_pass"

    until psql -h "$db_host" -p "$db_port" -U "$db_user" -d "$db_name" -c '\q' >/dev/null 2>&1; do
        echo "**** PostgreSQL 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 "**** PostgreSQL server at ${db_host}:${db_port} is available for ${db_name}."
}

psql_query(){
    query=$1
    export PGPASSWORD=${POSTGRES_JAZ_DB_PASSWORD}
    result=`psql --no-align --quiet --tuples-only --host=${JAZ_DB_SERVER_HOST} --port=${JAZDBPORT} --username=${POSTGRES_JAZ_DB_USER} --dbname=${POSTGRES_JAZ_DATABASE} --command "$query"`
    echo $result
}

### Check Database up or not ##### 

check_db_connect_postgres "$ZBX_DB_SERVER_HOST" "${DBPORT:-5432}" "$POSTGRES_ZBX_DB_USER" "$POSTGRES_ZBX_DB_PASSWORD" "$POSTGRES_ZBX_DATABASE"
check_db_connect_postgres "$JAZ_DB_SERVER_HOST" "${JAZDBPORT:-5432}" "$POSTGRES_JAZ_DB_USER" "$POSTGRES_JAZ_DB_PASSWORD" "$POSTGRES_JAZ_DATABASE"


##### Check Database exist or not only for JOBARRANGER #####
result=$(psql --tuples-only --quiet \
    --host "${JAZ_DB_SERVER_HOST}" --port "${JAZDBPORT:-5432}" --username "${POSTGRES_JAZ_DB_USER}" --dbname "${POSTGRES_JAZ_DATABASE}" \
    -c "SELECT COUNT(*) FROM pg_tables WHERE tablename LIKE 'ja_2%';" | xargs)

if [ "$result" = "0" ] || [ -z "$result" ]; then
    export LANG=C.UTF-8
    export PGPASSWORD="${POSTGRES_JAZ_DB_PASSWORD}"
    echo "***********CREATE DATABASE START*********** [${result}]"

    # Create tables
    psql --quiet --host "${JAZ_DB_SERVER_HOST}" --port "${JAZDBPORT:-5432}" --username "${POSTGRES_JAZ_DB_USER}" --dbname "${POSTGRES_JAZ_DATABASE}" \
         -f /usr/share/doc/jobarranger-server/database/postgresql/PostgreSQL_JA_CREATE_TABLE.sql || exit 1

    # Insert initial data
    psql --quiet --host "${JAZ_DB_SERVER_HOST}" --port "${JAZDBPORT:-5432}" --username "${POSTGRES_JAZ_DB_USER}" --dbname "${POSTGRES_JAZ_DATABASE}" \
         -f /usr/share/doc/jobarranger-server/database/data/JA_2_INSERT_TABLE.sql || exit 1

    echo "***********CREATE DATABASE END***********"
else
    if expr "$result" : "[0-9]*$" >/dev/null; then
        echo "********* There are [${result}] tables *******"
    else
        echo "********* Create table error ******* [${result}] *******"
        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"