#!/bin/bash

set -e

escape_spec_char() {
    local var_value=$1

    var_value="${var_value//\\/\\\\}"
    var_value="${var_value//[$'\n']/}"
    var_value="${var_value//\//\\/}"
    var_value="${var_value//./\\.}"
    var_value="${var_value//\*/\\*}"
    var_value="${var_value//^/\\^}"
    var_value="${var_value//\$/\\\$}"
    var_value="${var_value//\&/\\\&}"
    var_value="${var_value//\[/\\[}"
    var_value="${var_value//\]/\\]}"

    echo $var_value
}

update_config_var() {
    local config_path=$1
    local var_name=$2
    local var_value=$3
    local is_multiple=$4

    if [ ! -f "$config_path" ]; then
        echo "**** Configuration file '$config_path' does not exist"
        return
    fi

    echo -n "** Updating '$config_path' parameter \"$var_name\": '$var_value'... "

    # Remove configuration parameter definition in case of unset parameter value
    if [ -z "$var_value" ]; then
        sed -i -e "/^$var_name=/d" "$config_path"
        echo "removed"
        return
    fi

    # Remove value from configuration parameter in case of double quoted parameter value
    if [ "$var_value" == '""' ]; then
        sed -i -e "/^$var_name=/s/=.*/=/" "$config_path"
        echo "NULL"
        return
    fi

    # Escaping characters in parameter value
    var_value=$(escape_spec_char "$var_value")

    if [ "$(grep -E "^$var_name=" $config_path)" ] && [ "$is_multiple" != "true" ]; then
        sed -i -e "/^$var_name=/s/=.*/=$var_value/" "$config_path"
        echo "updated"
    elif [ "$(grep -Ec "^# $var_name=" $config_path)" -gt 1 ]; then
        sed -i -e  "/^[#;] $var_name=$/i\\$var_name=$var_value" "$config_path"
        echo "added first occurrence"
    else
        sed -i -e "/^[#;] $var_name=/s/.*/&\n$var_name=$var_value/" "$config_path"
        echo "added"
    fi

}

echo "***********LOG START*********"


##### Default Config Value #####

JOBARRANGER_ETC_DIR=/etc/jobarranger
JAZ_CONFIG=${JOBARRANGER_ETC_DIR}/jobarg_server.conf

INCLUDE=${INCLUDE:-""}
TMPDIR=${TMPDIR:-"/var/lib/jobarranger/server"}
UNIXSOCKPARENTDIR=${UNIXSOCKPARENTDIR:-"/usr/local/bin/jobarranger/server_socks"}
SERVERID=${SERVERID:-1}
JAPURGELIMIT=${JAPURGELIMIT:-500}
JAPURGETIME=${JAPURGETIME:-"00:00-00:00"}
LOGSLOWQUERIES=${LOGSLOWQUERIES:-0}
LISTENIP=${LISTENIP:-"0.0.0.0"}
SOURCEIP=${SOURCEIP:-""}
TIMEOUT=${TIMEOUT:-5}
DEBUGLEVEL=${DEBUGLEVEL:-3}
LOGFILESIZE=${LOGFILESIZE:-10}
LOGTYPE=${LOGTYPE:-"file"}
JOBNETMANAGERMAXDBCONCOUNT=${JOBNETMANAGERMAXDBCONCOUNT:-6}
FLOWMANAGERMAXDBCONCOUNT=${FLOWMANAGERMAXDBCONCOUNT:-2}
ICONRESULTMANAGERMAXDBCONCOUNT=${ICONRESULTMANAGERMAXDBCONCOUNT:-2}
ZABBIXLINKMANAGERMAXDBCONCOUNT=${ZABBIXLINKMANAGERMAXDBCONCOUNT:-3}
TIMERMANAGERMAXDBCONCOUNT=${TIMERMANAGERMAXDBCONCOUNT:-2}
HOUSEKEEPERMANAGERMAXDBCONCOUNT=${HOUSEKEEPERMANAGERMAXDBCONCOUNT:-4}
NOTIFICATIONMANAGERMAXDBCONCOUNT=${NOTIFICATIONMANAGERMAXDBCONCOUNT:-3}
DBSYNCERMANAGERMAXDBCONCOUNT=${DBSYNCERMANAGERMAXDBCONCOUNT:-4}
RECOVERYMANAGERMAXDBCONCOUNT=${RECOVERYMANAGERMAXDBCONCOUNT:-3}
DBPASSWORDEXTERNAL=${DBPASSWORDEXTERNAL:-""}
DBSOCKET=${DBSOCKET:-"/tmp/mysql.sock"}
JAZDBPASSWORDEXTERNAL=${JAZDBPASSWORDEXTERNAL:-""}
JAZDBSOCKET=${JAZDBSOCKET:-"/tmp/mysql.sock"}
MARIADBPLUGIN=${MARIADBPLUGIN:-"/usr/local/bin/jobarranger/maria_database.so"}
MYSQLDBPLUGIN=${MYSQLDBPLUGIN:-"/usr/local/bin/jobarranger/mysql_database.so"}
POSTGRESDBPLUGIN=${POSTGRESDBPLUGIN:-"/usr/local/bin/jobarranger/psql_database.so"}
MARIADBRETRYCODES=${MARIADBRETRYCODES:-"1213,1205,2006,2013,1040"}
MYSQLDBRETRYCODES=${MYSQLDBRETRYCODES:-"1213,1205,2006,2013,1040"}
POSTGRESDBRETRYCODES=${POSTGRESDBRETRYCODES:-"08000,08003,08006,08001,08004,08007,08P01,40000,40002,40001,40003,40P01,53000,53100,53200,53300,53400,55000,55006,55P02,55P03,55P04,57000,57014,57P01,57P02,57P03,57P04,57P05"}
DBTLSCONNECT=${DBTLSCONNECT:-""}
DBTLSCAFILE=${DBTLSCAFILE:-""}
DBTLSCERTFILE=${DBTLSCERTFILE:-""}
DBTLSKEYFILE=${DBTLSKEYFILE:-""}
DBTLSCIPHER=${DBTLSCIPHER:-""}
DBTLSCIPHER13=${DBTLSCIPHER13:-""}
JAZDBTLSCONNECT=${JAZDBTLSCONNECT:-""}
JAZDBTLSCAFILE=${JAZDBTLSCAFILE:-""}
JAZDBTLSCERTFILE=${JAZDBTLSCERTFILE:-""}
JAZDBTLSKEYFILE=${JAZDBTLSKEYFILE:-""}
JAZDBTLSCIPHER=${JAZDBTLSCIPHER:-""}
JAZDBTLSCIPHER13=${JAZDBTLSCIPHER13:-""}
JOBNETMANAGERTRANSACTIONTIMEOUT=${JOBNETMANAGERTRANSACTIONTIMEOUT:-60}
DBSYNCERMANAGERTRANSACTIONTIMEOUT=${DBSYNCERMANAGERTRANSACTIONTIMEOUT:-60}
FLOWMANAGERTRANSACTIONTIMEOUT=${FLOWMANAGERTRANSACTIONTIMEOUT:-60}
ICONEXECMANAGERTRANSACTIONTIMEOUT=${ICONEXECMANAGERTRANSACTIONTIMEOUT:-60}
ICONRESULTMANAGERTRANSACTIONTIMEOUT=${ICONRESULTMANAGERTRANSACTIONTIMEOUT:-60}
NOTIFICATIONMANAGERTRANSACTIONTIMEOUT=${NOTIFICATIONMANAGERTRANSACTIONTIMEOUT:-60}
INITIALSTARTTIME=${INITIALSTARTTIME:-600}
JACHANGESTATUSTIME=${JACHANGESTATUSTIME:-43200}
RUNRECORDMOVETIME=${RUNRECORDMOVETIME:-3600}
ARCHIVEINTERVAL=${ARCHIVEINTERVAL:-600}
JAEXTJOBWAITTIME=${JAEXTJOBWAITTIME:-300}
JALOGFILE=${JALOGFILE:-"/tmp/jobarg_server.log"}
JALOADERINTERVAL=${JALOADERINTERVAL:-30}
JACHECKJOBINTERVAL=${JACHECKJOBINTERVAL:-60}
JAICONRETRY=${JAICONRETRY:-30}
JARUNINTERVAL=${JARUNINTERVAL:-1}
JAMSGSNDINTERVAL=${JAMSGSNDINTERVAL:-1}
JATRAPPERLISTENPORT=${JATRAPPERLISTENPORT:-10061}
JAAGENTLISTENPORT=${JAAGENTLISTENPORT:-10055}
JALOGMESSAGEFILE=${JALOGMESSAGEFILE:-"/etc/jobarranger/locale/server_logmessage_64BIT.txt"}
JAFCOPYTIMEOUT=${JAFCOPYTIMEOUT:-180}
JALOADERTIMEOUT=${JALOADERTIMEOUT:-600}
JAMSNDTIMEOUT=${JAMSNDTIMEOUT:-600}
JAPURGETIMEOUT=${JAPURGETIMEOUT:-600}
JACHECKJOBTIMEOUT=${JACHECKJOBTIMEOUT:-1800}
JALAUNCHINTERVAL=${JALAUNCHINTERVAL:-1}
JAZABIXMESSAGEFILE=${JAZABIXMESSAGEFILE:-"/etc/jobarranger/locale"}
JAZEXECUTIONUSER=${JAZEXECUTIONUSER:-"zabbix"}
JAZABBIXURL=${JAZABBIXURL:-"http://127.0.0.1/zabbix"}
AGENTLESSREGEX=${AGENTLESSREGEX:-"\\x1b\\[[0-9;]*[a-zA-Z]|\\x1b][^\\x07]*\\x07|\\x1b\\[\\?2004[l,h]"}
JAZ1SUPPORT=${JAZ1SUPPORT:-0}
ICONSTOPINTERVAL=${ICONSTOPINTERVAL:-60}
GCINTERVAL=${GCINTERVAL:-5}

##### Update Config File #####
update_config_var $JAZ_CONFIG "Include" "${INCLUDE}"
update_config_var $JAZ_CONFIG "TmpDir" "${TMPDIR}"
update_config_var $JAZ_CONFIG "UnixSockParentDir" "${UNIXSOCKPARENTDIR}"
update_config_var $JAZ_CONFIG "JobnetManagerMaxDBConCount" "${JOBNETMANAGERMAXDBCONCOUNT}"
update_config_var $JAZ_CONFIG "FlowManagerMaxDBConCount" "${FLOWMANAGERMAXDBCONCOUNT}"
update_config_var $JAZ_CONFIG "IconResultManagerMaxDBConCount" "${ICONRESULTMANAGERMAXDBCONCOUNT}"
update_config_var $JAZ_CONFIG "ZabbixLinkManagerMaxDBConCount" "${ZABBIXLINKMANAGERMAXDBCONCOUNT}"
update_config_var $JAZ_CONFIG "TimerManagerMaxDBConCount" "${TIMERMANAGERMAXDBCONCOUNT}"
update_config_var $JAZ_CONFIG "HousekeeperManagerMaxDBConCount" "${HOUSEKEEPERMANAGERMAXDBCONCOUNT}"
update_config_var $JAZ_CONFIG "NotificationManagerMaxDBConCount" "${NOTIFICATIONMANAGERMAXDBCONCOUNT}"
update_config_var $JAZ_CONFIG "DBSyncerManagerMaxDBConCount" "${DBSYNCERMANAGERMAXDBCONCOUNT}"
update_config_var $JAZ_CONFIG "RecoveryManagerMaxDBConCount" "${RECOVERYMANAGERMAXDBCONCOUNT}"
update_config_var $JAZ_CONFIG "DBPasswordExternal" "${DBPASSWORDEXTERNAL}"
update_config_var $JAZ_CONFIG "DBSocket" "${DBSOCKET}"
update_config_var $JAZ_CONFIG "JazDBPasswordExternal" "${JAZDBPASSWORDEXTERNAL}"
update_config_var $JAZ_CONFIG "JazDBSocket" "${JAZDBSOCKET}"
update_config_var $JAZ_CONFIG "MariaDBPlugin" "${MARIADBPLUGIN}"
update_config_var $JAZ_CONFIG "MysqlDBPlugin" "${MYSQLDBPLUGIN}"
update_config_var $JAZ_CONFIG "PostgresDBPlugin" "${POSTGRESDBPLUGIN}"
update_config_var $JAZ_CONFIG "MariaDBRetryCodes" "${MARIADBRETRYCODES}"
update_config_var $JAZ_CONFIG "MysqlDBRetryCodes" "${MYSQLDBRETRYCODES}"
update_config_var $JAZ_CONFIG "PostgresDBRetryCodes" "${POSTGRESDBRETRYCODES}"
update_config_var $JAZ_CONFIG "DBTLSConnect" "${DBTLSCONNECT}"
update_config_var $JAZ_CONFIG "DBTLSCAFile" "${DBTLSCAFILE}"
update_config_var $JAZ_CONFIG "DBTLSCertFile" "${DBTLSCERTFILE}"
update_config_var $JAZ_CONFIG "DBTLSKeyFile" "${DBTLSKEYFILE}"
update_config_var $JAZ_CONFIG "DBTLSCipher" "${DBTLSCIPHER}"
update_config_var $JAZ_CONFIG "DBTLSCipher13" "${DBTLSCIPHER13}"
update_config_var $JAZ_CONFIG "JazDBTLSConnect" "${JAZDBTLSCONNECT}"
update_config_var $JAZ_CONFIG "JazDBTLSCAFile" "${JAZDBTLSCAFILE}"
update_config_var $JAZ_CONFIG "JazDBTLSCertFile" "${JAZDBTLSCERTFILE}"
update_config_var $JAZ_CONFIG "JazDBTLSKeyFile" "${JAZDBTLSKEYFILE}"
update_config_var $JAZ_CONFIG "JazDBTLSCipher" "${JAZDBTLSCIPHER}"
update_config_var $JAZ_CONFIG "JazDBTLSCipher13" "${JAZDBTLSCIPHER13}"
update_config_var $JAZ_CONFIG "ServerID" "${SERVERID}"
update_config_var $JAZ_CONFIG "JaPurgeLimit" "${JAPURGELIMIT}"
update_config_var $JAZ_CONFIG "JaPurgeTime" "${JAPURGETIME}"
update_config_var $JAZ_CONFIG "LogSlowQueries" "${LOGSLOWQUERIES}"
update_config_var $JAZ_CONFIG "ListenIP" "${LISTENIP}"
update_config_var $JAZ_CONFIG "SourceIP" "${SOURCEIP}"
update_config_var $JAZ_CONFIG "Timeout" "${TIMEOUT}"
update_config_var $JAZ_CONFIG "DebugLevel" "${DEBUGLEVEL}"
update_config_var $JAZ_CONFIG "LogFileSize" "${LOGFILESIZE}"
update_config_var $JAZ_CONFIG "LogType" "${LOGTYPE}"
update_config_var $JAZ_CONFIG "JobnetManagerTransactionTimeout" "${JOBNETMANAGERTRANSACTIONTIMEOUT}"
update_config_var $JAZ_CONFIG "DBSyncerManagerTransactionTimeout" "${DBSYNCERMANAGERTRANSACTIONTIMEOUT}"
update_config_var $JAZ_CONFIG "FlowManagerTransactionTimeout" "${FLOWMANAGERTRANSACTIONTIMEOUT}"
update_config_var $JAZ_CONFIG "IconExecManagerTransactionTimeout" "${ICONEXECMANAGERTRANSACTIONTIMEOUT}"
update_config_var $JAZ_CONFIG "IconResultManagerTransactionTimeout" "${ICONRESULTMANAGERTRANSACTIONTIMEOUT}"
update_config_var $JAZ_CONFIG "NotificationManagerTransactionTimeout" "${NOTIFICATIONMANAGERTRANSACTIONTIMEOUT}"
update_config_var $JAZ_CONFIG "InitialStartTime" "${INITIALSTARTTIME}"
update_config_var $JAZ_CONFIG "JaChangeStatusTime" "${JACHANGESTATUSTIME}"
update_config_var $JAZ_CONFIG "RunRecordMoveTime" "${RUNRECORDMOVETIME}"
update_config_var $JAZ_CONFIG "ArchiveInterval" "${ARCHIVEINTERVAL}"
update_config_var $JAZ_CONFIG "JaExtjobWaitTime" "${JAEXTJOBWAITTIME}"
update_config_var $JAZ_CONFIG "JaLogFile" "${JALOGFILE}"
update_config_var $JAZ_CONFIG "JaLoaderInterval" "${JALOADERINTERVAL}"
update_config_var $JAZ_CONFIG "JaCheckJobInterval" "${JACHECKJOBINTERVAL}"
update_config_var $JAZ_CONFIG "JaIconRetry" "${JAICONRETRY}"
update_config_var $JAZ_CONFIG "JaRunInterval" "${JARUNINTERVAL}"
update_config_var $JAZ_CONFIG "JaMsgsndInterval" "${JAMSGSNDINTERVAL}"
update_config_var $JAZ_CONFIG "JaTrapperListenPort" "${JATRAPPERLISTENPORT}"
update_config_var $JAZ_CONFIG "JaAgentListenPort" "${JAAGENTLISTENPORT}"
update_config_var $JAZ_CONFIG "JaLogMessageFile" "${JALOGMESSAGEFILE}"
update_config_var $JAZ_CONFIG "JaFcopyTimeout" "${JAFCOPYTIMEOUT}"
update_config_var $JAZ_CONFIG "JaLoaderTimeout" "${JALOADERTIMEOUT}"
update_config_var $JAZ_CONFIG "JaMsgsndTimeout" "${JAMSNDTIMEOUT}"
update_config_var $JAZ_CONFIG "JaPurgeTimeout" "${JAPURGETIMEOUT}"
update_config_var $JAZ_CONFIG "JaCheckJobTimeout" "${JACHECKJOBTIMEOUT}"
update_config_var $JAZ_CONFIG "JaLaunchInterval" "${JALAUNCHINTERVAL}"
update_config_var $JAZ_CONFIG "JaZabbixMessageFile" "${JAZABIXMESSAGEFILE}"
update_config_var $JAZ_CONFIG "JaExecutionUser" "${JAZEXECUTIONUSER}"
update_config_var $JAZ_CONFIG "JaZabbixURL" "${JAZABBIXURL}"
update_config_var $JAZ_CONFIG "AgentLessRegex" "${AGENTLESSREGEX}"
update_config_var $JAZ_CONFIG "Jaz1Support" "${JAZ1SUPPORT}"
update_config_var $JAZ_CONFIG "IconStopInterval" "${ICONSTOPINTERVAL}"
update_config_var $JAZ_CONFIG "GCInterval" "${GCINTERVAL}"

