#!/bin/bash
#----
## @Synopsis	This file contains functions to be used by Centreon install scripts
## @Copyright	Copyright 2008, Guillaume Watteeux
## @Copyright	Copyright 2008-2020, Centreon
## @Licence	GPLv2
## This file contains functions to be used by Centreon install scripts
#----
## Centreon is developed with GPL Licence 2.0
##
## GPL License: http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt
##
## Developed by : Julien Mathis - Romain Le Merlus
## Contributors : Guillaume Watteeux - Maximilien Bersoult
##
## This program 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 2
## of the License, or (at your option) any later version.
##
## This program 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.
##
##    For information : infos@centreon.com

# debug ?
#set -x

## VARS
yes="$(gettext "y")"
no="$(gettext "n")"
ok="$(gettext "OK")"
fail="$(gettext "FAIL")"
passed="$(gettext "PASSED")"
warning="$(gettext "WARNING")"
critical="$(gettext "CRITICAL")"
# Init binary to empty to use pathfind or manual define
GREP=""
CAT=""
SED=""
CHMOD=""
CHOWN=""

## COLOR FUNCTIONS

RES_COL="60"
MOVE_TO_COL="\\033[${RES_COL}G"
SETCOLOR_INFO="\\033[1;38m"
SETCOLOR_SUCCESS="\\033[1;32m"
SETCOLOR_FAILURE="\\033[1;31m"
SETCOLOR_WARNING="\\033[1;33m"
SETCOLOR_NORMAL="\\033[0;39m"

#----
## print info message
## add info message to log file
## @param	message info
## @param	type info (ex: INFO, username...)
## @Stdout	info message
## @Globals	LOG_FILE
#----
echo_info() {
    echo -e "${1}${MOVE_TO_COL}${SETCOLOR_INFO}${2}${SETCOLOR_NORMAL}"
    echo -e "$1 : $2" >> $LOG_FILE
}

#----
## Trim whitespaces and tabulations
## @param	string to trim
## @return	string
#----
trim() {
    echo "$1" | sed 's/^[ \t]*\(.*\)[ \t]*$/\1/'
}

#----
## print success message
## add success message to log file
## @param	message
## @param	word to specify success (ex: OK)
## @Stdout	success message
## @Globals	LOG_FILE
#----
echo_success() {
    echo -e "${1}${MOVE_TO_COL}${SETCOLOR_SUCCESS}${2}${SETCOLOR_NORMAL}"
    echo -e "$1 : $2" >> $LOG_FILE
}

#----
## print failure message
## add failure message to log file
## @param	message
## @param	word to specify failure (ex: fail)
## @Stdout	failure message
## @Globals	LOG_FILE
#----
echo_failure() {
    echo -e "${1}${MOVE_TO_COL}${SETCOLOR_FAILURE}${2}${SETCOLOR_NORMAL}"
    echo -e "$1 : $2" >> $LOG_FILE
}

#----
## print passed message
## add passed message to log file
## @param	message
## @param	word to specify pass (ex: passed)
## @Stdout	passed message
## @Globals	LOG_FILE
#----
echo_passed() {
    echo -e "${1}${MOVE_TO_COL}${SETCOLOR_WARNING}${2}${SETCOLOR_NORMAL}"
    echo -e "$1 : $2" >> $LOG_FILE
}

#----
## print warning message
## add warning message to log file
## @param	message
## @param	word to specify warning (ex: warn)
## @Stdout	warning message
## @Globals	LOG_FILE
#----
echo_warning() {
    echo -e "${1}${MOVE_TO_COL}${SETCOLOR_WARNING}${2}${SETCOLOR_NORMAL}"
    echo -e "$1 : $2" >> $LOG_FILE
}

#----
## add message on log file
## @param	type of message level (debug, info, ...)
## @param	message
## @Globals	LOG_FILE
#----
log() {
    local program="$0"
    local type="$1"
    shift
    local message="$@"
    echo -e "[$program]:$type: $message" >> $LOG_FILE
}


# FUNCTIONS
#----
## find in $PATH if binary exist
## @param	file to test
## @return 0	found
## @return 1	not found
## @Globals	PATH
#----
pathfind() {
    OLDIFS="$IFS"
    IFS=:
    for p in $PATH; do
        if [ -x "$p/$*" ]; then
            IFS="$OLDIFS"
            return 0
        fi
    done
    IFS="$OLDIFS"
    return 1
}

#----
## find in $PATH if binary exist and return dirname
## @param	file to test
## @param	global variable to set a result
## @return 0	found
## @return 1	not found
## @Globals	PATH
#----
pathfind_ret() {
    local bin=$1
    local var_ref=$2
    local OLDIFS="$IFS"
    IFS=:
    for p in $PATH; do
        if [ -x "$p/$bin" ]; then
            IFS="$OLDIFS"
            eval $var_ref=$p
            return 0
        fi
    done
    IFS="$OLDIFS"
    return 1
}

#----
## define a specific variables for grep,cat,sed,... binaries
## This functions was been use in first line on your script
## @return 0	All is't ok
## @return 1	problem with one variable
## @Globals	GREP, CAT, SED, CHMOD, CHOWN
#----
define_specific_binary_vars() {
    local vars_bin="GREP CAT SED CHMOD CHOWN"
    local var_bin_tolower=""
    for var_bin in $vars_bin ; do
        if [ -z $(eval echo \$$var_bin) ] ; then
            var_bin_tolower="$(echo $var_bin | tr [:upper:] [:lower:])"
            pathfind_ret "$var_bin_tolower" "$(echo -n $var_bin)"
            if [ "$?" -eq 0 ] ; then
                eval "$var_bin='$(eval echo \$$var_bin)/$var_bin_tolower'"
                export $(echo $var_bin)
                log "INFO" "$var_bin=$(eval echo \$$var_bin)"
            else
                return 1
            fi
        fi
    done
    return 0
}

#----
## make a question with yes/no possiblity
## use "no" response by default
## @param	message to print
## @param 	default response (default to no)
## @return 0 	yes
## @return 1 	no
#----
yes_no_default() {
    local message=$1
    local default=${2:-$no}
    local res="not_define"
    while [ "$res" != "$yes" ] && [ "$res" != "$no" ] && [ ! -z "$res" ] ; do
        echo -e "\n$message\n$(gettext "[y/n], default to") [$default]:"
        echo -en "> "
        read res
        [ -z "$res" ] && res="$default"
    done
    if [ "$res" = "$yes" ] ; then
        return 0
    else
        return 1
    fi
}

#----
## print a message, simple answer to the question
#----
answer() {
    local message=$1
    local default=$2
    local var_ref=$3
    local res=""
    local first=0
    while [ '!' -z "$res" ] ; do
        echo -e "\n$message"
        [ "$default" != "NO_DEFAULT" ] && echo -e "$(gettext "default to") [$default]"
        echo -en "> "
        read res
        if [ -z "$res" ] ; then
            [ "$default" != "NO_DEFAULT" ] && res=$default
        fi
    done
    eval $var_ref=$res
    return 0
}

#----
## print a message, test directory if answer is correct
## Loop if not a valid directory
## @param	message
## @param	default value (use "NO_DEFAULT" if not default value)
## @param	global variable to set a result
## @return 0	end
#----
answer_with_testdir() {
    local message=$1
    local default=$2
    local var_ref=$3
    local res="not_define"
    local first=0
    while [ ! -d "$res" ] ; do
        [ $first -eq 1 ] && echo_passed "$res $(gettext "is not a directory or does not exist.")" "$critical"
        echo -e "\n$message"
        [ "$default" != "NO_DEFAULT" ] && echo -e "$(gettext "default to") [$default]"
        echo -en "> "
        read res
        if [ -z "$res" ] ; then
            [ "$default" != "NO_DEFAULT" ] && res=$default
        fi
        if [ -z ${res#/} ] ; then
            echo_passed  "$(gettext "You cannot select slash")"
            res="not_define"
        else
            first=1
        fi
    done
    eval $var_ref=$res
    return 0
}

#----
## print a message, create directory with answer
## Loop if not a valid directory (slash...)
## @param	message
## @param	default value (use "NO_DEFAULT" if not default value)
## @param	global variable to set a result
## @return 0	end
#----
answer_with_createdir() {
    local message=$1
    local default=$2
    local var_ref=$3
    local res="not_define"
    local first=0
    while [ ! -d "$res" ] ; do
        [ $first -eq 1 ] && echo_passed "$(gettext "Directory $res does not exists.")" "$critical"
        echo -e "\n$message"
        [ "$default" != "NO_DEFAULT" ] && echo -e "$(gettext "default to") [$default]"
        echo -en "> "
        read res
        if [ -z "$res" ] ; then
            [ "$default" != "NO_DEFAULT" ] && res=$default
        fi
        if [ -z "${res#/}" -o "$yes" = "$res" -o "$no" = "$res" ] ; then
            echo_passed  "$(gettext "You cannot select slash")"
            res="not_define"
        else
            first=1
            [ -d "$res" ] && break
            yes_no_default "$(gettext "Do you want to create this directory?") [$res]"
            if [ $? -eq 0 ] ; then
                mkdir -p $res
                if [ $? -ne 0 ] ; then
                    echo_passed "$(gettext "Could not create directory.")" "$critical"
                    #continue
                fi
                log "INFO" "$(gettext "Creating") : $res"
            fi
        fi
    done
    eval $var_ref=$res
    return 0
}

#----
## print a message, create file if file not exists
## Loop if not a valid file
## @param       message
## @param       default value (use "NO_DEFAULT" if not default value)
## @param       global variable to set a result
## @return 0    end
#----
answer_with_createfile() {
    local message=$1
    local default=$2
    local var_ref=$3
    local res="not_define"
    local first=0
    while [ ! -f "$res" ] ; do
        [ $first -eq 1 ] && echo_passed "$(gettext "File $res does not exists.")" "$critical"
        echo -e "\n$message"
        [ "$default" != "NO_DEFAULT" ] && echo -e "$(gettext "default to") [$default]"
        echo -en "> "
        read res
        if [ -z "$res" ] ; then
            [ "$default" != "NO_DEFAULT" ] && res=$default
        fi
        if [ -z "${res#/}" -o "$yes" = "$res" -o "$no" = "$res" ] ; then
            echo_passed  "$(gettext "You cannot select slash")"
            res="not_define"
        else
            first=1
            [ -f "$res" ] && break
            yes_no_default "$(gettext "Do you want to create this file?") [$res]"
            if [ $? -eq 0 ] ; then
                touch $res
                if [ $? -ne 0 ] ; then
                    echo_passed "$(gettext "Could not create the file.")" "$critical"
                    #continue
                fi
                log "INFO" "$(gettext "Creating") : $res"
            fi
        fi
    done
    eval $var_ref=$res
    return 0
}

#----
## print a message, test if file exists
## Loop if not a valid file
## @param	message
## @param	default value (use "NO_DEFAULT" if not default value)
## @param	global variable to set a result
## @return 0	end
#----
answer_with_testfile() {
    local message=$1
    local default=$2
    local var_ref=$3
    local res="not_define"
    local first=0
    while [ ! -f "$res" ] ; do
        [ $first -eq 1 ] && echo_passed "$(gettext "$res is not a valid file.")" "$critical"
        echo -e "\n$message"
        [ "$default" != "NO_DEFAULT" ] && echo -e "$(gettext "default to") [$default]"
        echo -en "> "
        read res
        if [ -z "$res" ] ; then
            [ "$default" != "NO_DEFAULT" ] && res=$default
        fi
        first=1
    done
    eval $var_ref=$res
    return 0
}

#----
## print a message for get informations with create a group system
## @param	message
## @param	default value (use "NO_DEFAULT" if not default value)
## @param	global variable to set a result
## @return 0	end
#----
answer_with_creategroup() {
    local message=$1
    local default=$2
    local var_ref=$3
    local res="not_def"
    local first=0
    local group_tested=1
    while [ "$group_tested" -ne 0 ] ; do
        [ $first -eq 1 ] && echo_passed "$(gettext "The group $res does not exist.")" "$critical"
        echo -e "\n$message"
        [ "$default" != "NO_DEFAULT" ] && echo -e "$(gettext "default to") [$default]"
        echo -en "> "
        read res
        if [ -z "$res" ]; then
            [ "$default" != "NO_DEFAULT" ] && res=$default
        fi
        first=1
        if [ -n "$res" ]; then
            group_test "$res"
            if [ $? -ne 0 ] ; then
                yes_no_default "$(gettext "Do you want to create this group?") [$res]"
                if [ $? -eq 0 ]; then
                    group_create "$res"
                fi
            fi
        else
            res="not_def"
        fi
        group_test "$res"
        group_tested=$?
    done
    eval "$var_ref"="$res"
    return 0
}

#----
## print a message for get informations with create a user system
## @param	message
## @param	default value (use "NO_DEFAULT" if not default value)
## @param	global variable to set a result
## @return 0	end
#----
answer_with_createuser() {
    local message=$1
    local default=$2
    local var_ref=$3
    local groups="$4"
    local description="$5"
    local home="$6"
    local res="not_def"
    local first=0
    local user_tested=1
    while [ "$user_tested" -ne 0 ] ; do
        [ $first -eq 1 ] && echo_passed "$(gettext "The user $res does not exist.")" "$critical"
        echo -e "\n$message"
        [ "$default" != "NO_DEFAULT" ] && echo -e "$(gettext "default to") [$default]"
        echo -en "> "
        read res
        if [ -z "$res" ]; then
            [ "$default" != "NO_DEFAULT" ] && res=$default
        fi
        first=1
        if [ -n "$res" ]; then
            user_test "$res"
            if [ $? -ne 0 ] ; then
                yes_no_default "$(gettext "Do you want to create this user?") [$res]"
                if [ $? -eq 0 ] ; then
                    user_create "$res" "$groups" "$description" "$home"
                fi
            fi
        else
            res="not_def"
        fi
        user_test "$res"
        user_tested=$?
    done
    eval "$var_ref"="$res"
    return 0
}

#----
## print a message for get informations with test if user exists
## @param	message
## @param	default value (use "NO_DEFAULT" if not default value)
## @param	global variable to set a result
## @return 0	end
#----
answer_with_testuser() {
    local message=$1
    local default=$2
    local var_ref=$3
    local res="not_def"
    local first=0
    local user_tested=1
    while [ "$user_tested" -ne 0 ] ; do
        [ $first -eq 1 ] && echo_passed "$(gettext "The user $res does not exists.")" "$critical"
        echo -e "\n$message"
        [ "$default" != "NO_DEFAULT" ] && echo -e "$(gettext "default to") [$default]"
        echo -en "> "
        read res
        if [ -z "$res" ]; then
            [ "$default" != "NO_DEFAULT" ] && res=$default
        fi
        first=1
        user_test "$res"
        user_tested=$?
    done
    eval $var_ref=$res
    return 0
}

#----
## Test if file exist
## @param	file
## @param	variable to reset
## @return 0 	file exist
## @return 1 	file does not exist
#----
testfile_clean() {
    local file="$1"
    local var="$2"
    [ -z "$file" ] && return 1
    if [ ! -e "$file" ] ; then
        eval $var=""
        return 1
    else
        return 0
    fi
}

#----
## Test if directory exist
## @param	directory
## @param	variable to reset
## @return 0 directory exist
## @return 1 directory does not exist
#----
testdir_clean() {
    local dir="$1"
    local var="$2"
    [ -z "$dir" ] && return 1
    if [ ! -d "$dir" ] ; then
        eval $var=""
        return 1
    else
        return 0
    fi
}

dir_test_create() {
    local dirname="$1"
    if [ ! -d "$1" ] ; then
        mkdir -p "$dirname"
        if [ $? -ne 0 ] ; then
            echo_failure "$(gettext "Could not create directory") $dirname" "$fail"
            return 1
        fi
        echo_success "$(gettext "Creating directory") $dirname" "$ok"
    fi
    return 0
}

user_test() {
    grep "^$1:" /etc/passwd &>/dev/null
    return $?
}

user_create() {
    local username="$1"
    local groupname="$2"
    local description="$3"
    local home="$4"
    useradd -r -c "$description" -s "/bin/sh" -d "$home" -g "$groupname" "$username"
    if [ $? -ne 0 ]; then
        echo_failure "$(gettext "Could not create user") $username" "$fail"
        return 1
    fi
    echo_success "$(gettext "Creating user") $username ($description)" "$ok"
    return 0
}

group_test() {
    grep "^$1:" /etc/group &>/dev/null
    return $?
}

group_create() {
    local groupname="$1"
    groupadd -r "$groupname"
    if [ $? -ne 0 ] ; then
        echo_failure "$(gettext "Could not create group") $groupname" "$fail"
        return 1
    fi
    echo_success "$(gettext "Creating group") $groupname" "$ok"
    return 0
}

#----
## Define where is  plugins directory
## in last version of this script, you have been a possibility to create if not exist. now is not possible. You will create manualy.
## @Globals     PLUGIN_DIR, DEFAULT_PLUGIN_DIR
#----
locate_plugindir() {
    testdir_clean "$PLUGIN_DIR" "PLUGIN_DIR"
    if [ -z "$PLUGIN_DIR" ] ; then
        answer "$(gettext "Where is your monitoring plugins (libexec) directory?")" "$DEFAULT_PLUGIN_DIR" "PLUGIN_DIR"
        echo_success "$(gettext "Path" ) $PLUGIN_DIR" "$ok"
    fi
    PLUGIN_DIR=`trim ${PLUGIN_DIR%/}`
    export PLUGIN_DIR
    log "INFO" "PLUGIN_DIR: $PLUGIN_DIR"
}

#----
## Define where is your init.d (rc.d) directory
## check on system where is a init.d or rc.d directory to install centreon services
## On GNU/Linux, most of distrib use /etc/init.d
## On FreeBSD, use /usr/local/etc/rc.d
## It's possible to add most of directory.
## @Globals	INIT.D, DEFAULT_INIT_D
#----
locate_init_d() {
    testdir_clean "$INIT_D" "INIT_D"
    if [ -z "$INIT_D" ] ; then
        if [ -d "/etc/init.d" ] ; then
            INIT_D="/etc/init.d"
        elif [ -d "/usr/local/etc/rc.d" ] ; then
            INIT_D="/usr/local/etc/rc.d"
        # Add most of init.d
        else
            answer_with_testdir "$(gettext "Where is your init.d directory?")" "$DEFAULT_INIT_D" "INIT_D"
            echo_success "$(gettext "Path" ) $INIT_D" "$ok"
        fi
    fi
    INIT_D=`trim ${INIT_D%/}`
    export INIT_D
    log "INFO" "INIT_D: $INIT_D"
}

#----
## Define where is centreon plugins directory
## @Globals     CENTREON_PLUGINS, DEFAULT_CENTREON_PLUGINS
#----
locate_centreon_plugins() {
    testdir_clean "$CENTREON_PLUGINS" "CENTREON_PLUGINS"
    if [ -z "$CENTREON_PLUGINS" ] ; then
        answer "$(gettext "Where is your centreon plugins directory?")" "$DEFAULT_CENTREON_PLUGINS" "CENTREON_PLUGINS"
        echo_success "$(gettext "Path" ) $CENTREON_PLUGINS" "$ok"
    fi
    CENTREON_PLUGINS=`trim ${CENTREON_PLUGINS%/}`
    export CENTREON_PLUGINS
    log "INFO" "CENTREON_PLUGINS: $CENTREON_PLUGINS"
}

#----
## Define where is centreon gorgone module
## @Globals     GORGONE_VARLIB, DEFAULT_GORGONE_VARLIB
#----
locate_gorgone_varlib() {
    if [ -z "$GORGONE_VARLIB" ] ; then
        answer_with_testdir "$(gettext "Where is your gorgone module folder?") [$DEFAULT_GORGONE_VARLIB]" "$DEFAULT_GORGONE_VARLIB" "GORGONE_VARLIB"
    fi
    GORGONE_VARLIB=`trim ${GORGONE_VARLIB%/}`
    export GORGONE_VARLIB
    echo_success "$(gettext "Path" ) $GORGONE_VARLIB" "$ok"
    log "INFO" "GORGONE_VARLIB: $GORGONE_VARLIB"
}

#----
## Define where is centreon gorgone configuration folder
## @Globals     GORGONE_CONFIG, DEFAULT_GORGONE_CONFIG
#----
locate_gorgone_config() {
    if [ -z "$GORGONE_CONFIG" ] ; then
        answer_with_testdir "$(gettext "Where is your gorgone configuration folder?") [$DEFAULT_GORGONE_CONFIG]" "$DEFAULT_GORGONE_CONFIG" "GORGONE_CONFIG"
    fi
    GORGONE_CONFIG=`trim ${GORGONE_CONFIG%/}`
    export GORGONE_CONFIG
    log "INFO" "GORGONE_CONFIG: $GORGONE_CONFIG"
}


locate_monitoringengine_etc() {
    if [ -z "$MONITORINGENGINE_ETC" ]; then
        answer_with_testdir "$(gettext "What is the Monitoring engine configuration directory?") [$DEFAULT_MONITORINGENGINE_ETC]" "$DEFAULT_MONITORINGENGINE_ETC" "MONITORINGENGINE_ETC"
    fi
    MONITORINGENGINE_ETC=`trim ${MONITORINGENGINE_ETC%/}`
    export MONITORINGENGINE_ETC
    log "INFO" "MONITORINGENGINE_ETC: $MONITORINGENGINE_ETC"
}

locate_monitoringengine_log() {
    if [ -z "$MONITORINGENGINE_LOG" ]; then
        answer_with_testdir "$(gettext "What is the Monitoring engine log directory?") [$DEFAULT_MONITORINGENGINE_LOG]" "$DEFAULT_MONITORINGENGINE_LOG" "MONITORINGENGINE_LOG"
    fi
    MONITORINGENGINE_LOG=`trim ${MONITORINGENGINE_LOG%/}`
    export MONITORINGENGINE_LOG
    log "INFO" "MONITORINGENGINE_LOG: $MONITORINGENGINE_LOG"
}

locate_broker_etc() {
    if [ -z "$BROKER_ETC" ]; then
        answer_with_testdir "$(gettext "Where is the configuration directory for the broker module?") [$DEFAULT_BROKER_ETC]" "$DEFAULT_BROKER_ETC" "BROKER_ETC"
    fi
    BROKER_ETC=`trim ${BROKER_ETC%/}`
    export BROKER_ETC
    log "INFO" "BROKER_ETC: $BROKER_ETC"
}

#----
## Define where is Centreon log directory
## @Globals	CENTREON_LOG, DEFAULT_CENTREON_LOG
#----
locate_centreon_logdir() {
    if [ -n "$CENTREON_LOG" ] ; then
        dir_test_create "$CENTREON_LOG"
        if [ $? -ne 0 ] ; then
            CENTREON_LOG=""
        fi
    fi
    if [ -z "$CENTREON_LOG" ] ; then
        answer_with_createdir "$(gettext "Where is your Centreon log directory")" "$DEFAULT_CENTREON_LOG" "CENTREON_LOG"
        echo_success "$(gettext "Path" ) $CENTREON_LOG" "$ok"
    fi
    CENTREON_LOG=`trim ${CENTREON_LOG%/}`
    export CENTREON_LOG
    log "INFO" "CENTREON_LOG: $CENTREON_LOG"
}

#----
## Define where is Centreon etc (config) directory
## @Globals	CENTREON_ETC, DEFAULT_CENTREON_ETC
#----
locate_centreon_etcdir() {
    if [ -n "$CENTREON_ETC" ] ; then
        dir_test_create "$CENTREON_ETC"
        if [ $? -ne 0 ] ; then
            CENTREON_ETC=""
        fi
    fi
    if [ -z "$CENTREON_ETC" ] ; then
        answer_with_createdir "$(gettext "Where is your Centreon etc directory")" "$DEFAULT_CENTREON_ETC" "CENTREON_ETC"
        echo_success "$(gettext "Path" ) $CENTREON_ETC" "$ok"
    fi
    CENTREON_ETC=`trim ${CENTREON_ETC%/}`
    export CENTREON_ETC
    log "INFO" "CENTREON_ETC: $CENTREON_ETC"
}

#----
## Define where is Centreon bin directory
## CENTREON_BINDIR is the bin directory inside centreon directory
## @Globals	INSTALL_DIR_CENTREON
#----
locate_centreon_bindir() {
    CENTREON_BINDIR="$INSTALL_DIR_CENTREON/bin"
    export CENTREON_BINDIR
    log "INFO" "CENTREON_BINDIR: $CENTREON_BINDIR"
}

#----
## Define where is centreon install directory
## @Globals	INSTALL_DIR_CENTREON, DEFAULT_INSTALL_DIR_CENTREON
#----
locate_centreon_installdir() {
    if [ -n "$INSTALL_DIR_CENTREON" ] ; then
        dir_test_create "$INSTALL_DIR_CENTREON"
        if [ $? -ne 0 ] ; then
            INSTALL_DIR_CENTREON=""
        fi
    fi
    if [ -z "$INSTALL_DIR_CENTREON" ] ; then
        answer_with_createdir "$(gettext "Where is your Centreon directory?")" "$DEFAULT_INSTALL_DIR_CENTREON" "INSTALL_DIR_CENTREON"
        echo_success "$(gettext "Path" ) $INSTALL_DIR_CENTREON" "$ok"
    fi
    INSTALL_DIR_CENTREON=`trim ${INSTALL_DIR_CENTREON%/}`
    export INSTALL_DIR_CENTREON
    log "INFO" "INSTALL_DIR_CENTREON: $INSTALL_DIR_CENTREON"
}

#----
## Define where is Centreon generation directory
## Generation directory is use for a temporary config (same as INSTALL_DIR).
## @Globals	CENTREON_CACHEDIR, DEFAULT_CENTREON_CACHEDIR
#----
locate_centreon_generationdir() {
    if [ -n "$CENTREON_CACHEDIR" ] ; then
        dir_test_create "$CENTREON_CACHEDIR"
        if [ $? -ne 0 ] ; then
            CENTREON_CACHEDIR=""
        fi
    fi
    if [ -z "$CENTREON_CACHEDIR" ] ; then
        answer_with_createdir "$(gettext "Where is your Centreon cache directory?")" "$DEFAULT_CENTREON_CACHEDIR" "CENTREON_CACHEDIR"
        echo_success "$(gettext "Path" ) $CENTREON_CACHEDIR" "$ok"
    fi
    CENTREON_CACHEDIR=`trim ${CENTREON_CACHEDIR%/}`
    export CENTREON_CACHEDIR
    log "INFO" "CENTREON_CACHEDIR: $CENTREON_CACHEDIR"
}

#----
## Define where is Centreon run directory (for .run file)
## @Globals	CENTREON_RUNDIR, DEFAULT_CENTREON_RUNDIR
#----
locate_centreon_rundir() {
    if [ -n "$CENTREON_RUNDIR" ] ; then
        dir_test_create "$CENTREON_RUNDIR"
        if [ $? -ne 0 ] ; then
            CENTREON_RUNDIR=""
        fi
    fi
    if [ -z "$CENTREON_RUNDIR" ] ; then
        answer_with_createdir "$(gettext "Where is your Centreon Run Dir directory?")" "$DEFAULT_CENTREON_RUNDIR" "CENTREON_RUNDIR"
        echo_success "$(gettext "Path" ) $CENTREON_RUNDIR" "$ok"
    fi
    CENTREON_RUNDIR=`trim ${CENTREON_RUNDIR%/}`
    export CENTREON_RUNDIR
    log "INFO" "CENTREON_RUNDIR: $CENTREON_RUNDIR"
}

#----
## Define where is Centreon variable library directory
## @Globals	CENTREON_VARLIB, DEFAULT_CENTREON_VARLIB
#----
locate_centreon_varlib() {
    if [ -n "$CENTREON_VARLIB" ] ; then
        dir_test_create "$CENTREON_VARLIB"
        if [ $? -ne 0 ] ; then
            CENTREON_VARLIB=""
        fi
    fi
    if [ -z "$CENTREON_VARLIB" ] ; then
        answer_with_createdir "$(gettext "Where is your Centreon variable library directory?")" "$DEFAULT_CENTREON_VARLIB" "CENTREON_VARLIB"
        echo_success "$(gettext "Path" ) $CENTREON_VARLIB" "$ok"
    fi
    CENTREON_VARLIB=`trim ${CENTREON_VARLIB%/}`
    if [ ! -d "$CENTREON_VARLIB/installs" ] ; then
        mkdir -p "$CENTREON_VARLIB/installs"
    fi
    export CENTREON_VARLIB
    log "INFO" "CENTREON_VARLIB: $CENTREON_VARLIB"
}

#----
## Define where centStorage store a RRD file
## @Globals	CENTSTORAGE_RRD, DEFAULT_CENTSTORAGE_RRD
#----
locate_centstorage_rrddir() {
    if [ -n "$CENTSTORAGE_RRD" ] ; then
        dir_test_create "$CENTSTORAGE_RRD"
        if [ $? -ne 0 ] ; then
            CENTSTORAGE_RRD=""
        fi
    fi
    if [ -z "$CENTSTORAGE_RRD" ] ; then
        answer_with_createdir "$(gettext "Where is your CentStorage RRD directory")" "$DEFAULT_CENTSTORAGE_RRD" "CENTSTORAGE_RRD"
        echo_success "$(gettext "Path" ) $CENTSTORAGE_RRD" "$ok"
    fi
    CENTSTORAGE_RRD=`trim ${CENTSTORAGE_RRD%/}`
    export CENTSTORAGE_RRD
    log "INFO" "CENTSTORAGE_RRD: $CENTSTORAGE_RRD"
}

#----
## Define where is centStorage binary directory
## @Globals	CENTSTORAGE_BINDIR, INSTALL_DIR_CENTREON, DEFAULT_CENTSTORAGE_BINDIR
#----
locate_centstorage_bindir() {
    if [ -z "$CENTSTORAGE_BINDIR" ] ; then
        answer_with_createdir "$(gettext "Where is your CentStorage binary directory")" "$INSTALL_DIR_CENTREON/$DEFAULT_CENTSTORAGE_BINDIR" "CENTSTORAGE_BINDIR"
        echo_success "$(gettext "Path" ) $CENTSTORAGE_BINDIR" "$ok"
    elif [ ! -d "$CENTSTORAGE_BINDIR" -a "$silent_install" -eq 1 ] ; then
        mkdir -p "$CENTSTORAGE_BINDIR"
        log "INFO" "$(gettext "Create") $CENTSTORAGE_BINDIR"
    fi
    CENTSTORAGE_BINDIR=`trim ${CENTSTORAGE_BINDIR%/}`
    export CENTSTORAGE_BINDIR
    log "INFO" "CENTSTORAGE_BINDIR: $CENTSTORAGE_BINDIR"
}

#----
## Define where is centStorage library directory
## @Globals	CENTSTORAGE_LIBDIR, INSTALL_DIR_CENTREON, DEFAULT_CENTSTORAGE_LIBDIR
#----
locate_centstorage_libdir() {
    if [ -z "$CENTSTORAGE_LIBDIR" ] ; then
        answer_with_createdir "$(gettext "Where is your CentStorage library directory")" "$INSTALL_DIR_CENTREON/$DEFAULT_CENTSTORAGE_LIBDIR" "CENTSTORAGE_LIBDIR"
        echo_success "$(gettext "Path" ) $CENTSTORAGE_LIBDIR" "$ok"
    elif [ ! -d "$CENTSTORAGE_LIBDIR" -a "$silent_install" -eq 1 ] ; then
        mkdir -p "$CENTSTORAGE_LIBDIR"
        log "INFO" "$(gettext "Create") $CENTSTORAGE_LIBDIR"
    fi
    CENTSTORAGE_LIBDIR=`trim ${CENTSTORAGE_LIBDIR%/}`
    export CENTSTORAGE_LIBDIR
    log "INFO" "CENTSTORAGE_LIBDIR: $CENTSTORAGE_LIBDIR"
}

#----
## Define where is centPlugins temporary directory
## @Globals	CENTPLUGINS_TMP, DEFAULT_CENTPLUGINS_TMP
#----
locate_centplugins_tmpdir() {
    if [ -n "$CENTPLUGINS_TMP" ] ; then
        dir_test_create "$CENTPLUGINS_TMP"
        if [ $? -ne 0 ] ; then
            CENTPLUGINS_TMP=""
        else
            $CHMOD g+w "$CENTPLUGINS_TMP"
        fi
    fi
    if [ -z "$CENTPLUGINS_TMP" ] ; then
        answer_with_createdir "$(gettext "Where is your CentPlugins lib directory")" "$DEFAULT_CENTPLUGINS_TMP" "CENTPLUGINS_TMP"
        echo_success "$(gettext "Path" ) $CENTPLUGINS_TMP" "$ok"
    fi
    CENTPLUGINS_TMP=`trim ${CENTPLUGINS_TMP%/}`
    export CENTPLUGINS_TMP
    log "INFO" "CENTPLUGINS_TMP: $CENTPLUGINS_TMP"
}

#----
## Define where is SNMP etc (config) directory
## @Globals	SNMP_ETC, DEFAULT_SNMP_ETC
#----
locate_snmp_etcdir() {
    testdir_clean "$SNMP_ETC" "SNMP_ETC"
    if [ -z "$SNMP_ETC" ] ; then
        answer_with_testdir "$(gettext "Where is your SNMP configuration directory")" "$DEFAULT_SNMP_ETC" "SNMP_ETC"
        echo_success "$SNMP_ETC" "$ok"
    fi
    SNMP_ETC=${SNMP_ETC%/}
    export SNMP_ETC
    log "INFO" "SNMP_ETC: $SNMP_ETC"
}

#----
## Define where is CENTREONTRAPD binary directory
## @Globals	CENTREONTRAPD_BINDIR, DEFAULT_CENTREONTRAPD_BINDIR
#----
locate_centreontrapd_bindir() {
    if [ -z "$CENTREONTRAPD_BINDIR" ] ; then
        answer_with_createdir "$(gettext "Where is your CentreonTrapd binaries directory")" "$DEFAULT_CENTREON_BINDIR" "CENTREONTRAPD_BINDIR"
        echo_success "$CENTREONTRAPD_BINDIR" "$ok"
    fi
    CENTREONTRAPD_BINDIR=`trim ${CENTREONTRAPD_BINDIR%/}`
    export CENTREONTRAPD_BINDIR
    log "INFO" "CENTREONTRAPD_BINDIR: $CENTREONTRAPD_BINDIR"
}

#----
## Define where is Sudo file
## @Globals	SUDO_FILE, DEFAULT_SUDO_FILE
#----
locate_sudo() {
    if [ -z "$SUDO_FILE" ] ; then
        answer_with_createfile "$(gettext "Where is sudo configuration file")" "$DEFAULT_SUDO_FILE" "SUDO_FILE"
        echo_success "$SUDO_FILE" "$ok"
    fi
    SUDO_FILE=`trim ${SUDO_FILE%/}`
    export SUDO_FILE
    log "INFO" "SUDO_FILE: $SUDO_FILE"
}

#----
## Define where is rrdtool binary
## find rrdtool in PATH
## @Globals	BIN_RRDTOOL, DEFAULT_BIN_RRDTOOL
#----
locate_rrdtool() {
    testfile_clean "$BIN_RRDTOOL" "BIN_RRDTOOL"
    if [ -z "$BIN_RRDTOOL" ] ; then
        pathfind_ret "rrdtool" "BIN_RRDTOOL"
        if [ "$?" -ne 0 ] ; then
            answer_with_testfile "$(gettext "Where is rrdtool")" "$DEFAULT_BIN_RRDTOOL" "BIN_RRDTOOL"
        else
            BIN_RRDTOOL="$BIN_RRDTOOL/rrdtool"
        fi
        echo_success "$BIN_RRDTOOL" "$ok"
    fi
    BIN_RRDTOOL=`trim ${BIN_RRDTOOL%/}`
    export BIN_RRDTOOL
    log "INFO" "BIN_RRDTOOL: $BIN_RRDTOOL"
}

#----
## Define where is perl binary
## find perl in PATH
## @Globals	BIN_PERL, DEFAULT_BIN_PERL
#----
locate_perl() {
    testfile_clean "$BIN_PERL" "BIN_PERL"
    if [ -z "$BIN_PERL" ] ; then
        pathfind_ret "perl" "BIN_PERL"
        if [ "$?" -ne 0 ] ; then
            answer_with_testfile "$(gettext "Where is perl")" "$DEFAULT_BIN_PERL" "BIN_PERL"
        else
            BIN_PERL="$BIN_PERL/perl"
        fi
        echo_success "$BIN_PERL" "$ok"
    fi
    BIN_PERL=`trim ${BIN_PERL%/}`
    export BIN_PERL
    log "INFO" "BIN_PERL: $BIN_PERL"
}

#----
## Define where is mail binary
## find mail in PATH
## @Globals	BIN_MAIL, DEFAULT_BIN_MAIL
#----
locate_mail() {
    testfile_clean "$BIN_MAIL" "BIN_MAIL"
    if [ -z "$BIN_MAIL" ] ; then
        pathfind_ret "mail" "BIN_MAIL"
        if [ "$?" -ne 0 ] ; then
            answer_with_testfile "$(gettext "Where is mail binary")" "$DEFAULT_BIN_MAIL" "BIN_MAIL"
        else
            BIN_MAIL="$BIN_MAIL/mail"
        fi
        echo_success "$BIN_MAIL" "$ok"
    fi
    BIN_MAIL=`trim ${BIN_MAIL%/}`
    export BIN_MAIL
    log "INFO" "BIN_MAIL: $BIN_MAIL"
}

#----
## Define where is php binary
## find php, php5 in PATH
## @Globals	PHP_BIN, DEFAULT_PHP_BIN
#----
locate_php_bin() {
    testfile_clean "$PHP_BIN" "PHP_BIN"
    if [ -z "$PHP_BIN" ] ; then
        answer_with_testfile "$(gettext "Where is your php binary? ")" "$DEFAULT_PHP_BIN" "PHP_BIN"
        echo_success "$PHP_BIN" "$ok"
    fi
    PHP_BIN=`trim ${PHP_BIN%/}`
    export PHP_BIN
    log "INFO" "PHP_BIN: $PHP_BIN"
}

#----
## Define where is php-pear (PEAR.php)
## @Globals	PEAR_PATH, DEFAULT_PEAR_PATH
#----
locate_pear() {
    testdir_clean "$PEAR_PATH" "PEAR_PATH"
    if [ -z "$PEAR_PATH" ] ; then
        answer_with_testfile "$(gettext "Where is PEAR [PEAR.php] ")" "$DEFAULT_PEAR_PATH/PEAR.php" "PEAR_PATH"
        PEAR_PATH=$(dirname $PEAR_PATH)
        echo_success "$(gettext "Path" ) $PEAR_PATH" "$ok"
    fi
    PEAR_PATH=`trim ${PEAR_PATH%/}`
    export PEAR_PATH
    log "INFO" "PEAR_PATH: $PEAR_PATH"
}

#----
## Define where is your cron.d directory
## @Globals	CRON_D, DEFAULT_CRON_D
#----
locate_cron_d() {
    testdir_clean "$CRON_D" "CRON_D"
    if [ -z "$CRON_D" ] ; then
        if [ -d "/etc/cron.d" ] ; then
            CRON_D="/etc/cron.d"
        # Add most of init.d
        else
            answer_with_testdir "$(gettext "Where is your cron.d directory?")" "$DEFAULT_CRON_D" "CRON_D"
            echo_success "Path $CRON_D" "$ok"
        fi
    fi
    CRON_D=`trim ${CRON_D%/}`
    export CRON_D
    log "INFO" "CRON_D: $CRON_D"
}

#----
## Define where is your logrotate.d directory
## @Globals	LOGROTATE_D, DEFAULT_LOGROTATE_D
#----
locate_logrotate_d() {
    testdir_clean "$LOGROTATE_D" "LOGROTATE_D"
    if [ -z "$LOGROTATE_D" ] ; then
        if [ -d "/etc/logrotate.d" ] ; then
            LOGROTATE_D="/etc/logrotate.d"
        # Add most of init.d
        else
            answer_with_testdir "$(gettext "Where is your logrotate.d directory?")" "$DEFAULT_LOGROTATE_D" "LOGROTATE_D"
            echo_success "Path $LOGROTATE_D" "$ok"
        fi
    fi
    LOGROTATE_D=`trim ${LOGROTATE_D%/}`
    export LOGROTATE_D
    log "INFO" "LOGROTATE_D: $LOGROTATE_D"
}

#----
## Check php version which should be greater than the minimum version required
## @Globals	PHP_BIN, PHP_MIN_VERSION
#----
check_php_version() {
    log "INFO" "check php version"
    local php_version=$($PHP_BIN --version | head -n 1 | cut -d " " -f 2 | cut -c 1,3)
    if [ "$php_version" -lt "$PHP_MIN_VERSION" ] ; then
        echo_failure "$(gettext "Minimum PHP version required is : $PHP_MIN_VERSION")" "$fail"
        return 1
    else
        echo_success "$(gettext "check PHP version")" "$ok"
        return 0
    fi
}

#----
## Check if composer dependencies are installed (vendor directory)
## @Globals	INSTALL_DIR_CENTREON
#----
check_composer_dependencies() {
    if [ -d "$BASE_DIR/vendor" ] ; then
        echo_success "$(gettext "Composer dependencies are installed")" "$ok"
        return 0
    else
        echo_failure "$(gettext "Composer dependencies are not installed")" "$fail"
        return 1
    fi
}

#----
## Check if composer dependencies are installed (vendor directory)
## @Globals	INSTALL_DIR_CENTREON
#----
check_frontend_application() {
    if [ -d "$BASE_DIR/www/static" ] ; then
        echo_success "$(gettext "Frontend application is built")" "$ok"
        return 0
    else
        echo_failure "$(gettext "Frontend application is not built")" "$fail"
        return 1
    fi
}

#----
## Check if variable do not have most possibility
## @param	variable to check
## @return 0	True
## @return 1	False
#----
is_single() {
    local var="$1"

    local count=0
    for value in $var ; do
        let "count += 1"
    done

    if [ "$count" -eq 1 ] ; then
        return 0
    else
        return 1
    fi
}

#----
## Check apache version, and configure it. Ask to restart apache server
## Make a copy of the original file as httpd.conf.initial
## <p>
## Call <@function prepare_apache_config> and <@function reload_service_apache> function
## <p>
## @param	apache config directory
## @Globals	line, DIR_APACHE_CONF, LOG_FILE, silent_install
#----
configureApache() {
    echo -e "\n$line"
    echo -e "\t$(gettext "Configure Apache server")"
    echo -e "$line"

    local write_config="0"
    local dir_conf="$1"
    # Generate a apache config in directory
    prepare_apache_config "$dir_conf"

    if [ "$silent_install" -ne 1 ] ; then
        if [ -e $DIR_APACHE_CONF/centreon.conf ] ; then
            echo "$(gettext "Finding Apache Centreon configuration file")"
            echo_success "'$DIR_APACHE_CONF/centreon.conf' :" "$ok"
            yes_no_default "$(gettext "Do you want to update Centreon Apache sub configuration file?")"
            if [ "$?" -eq 0 ] ; then
                write_config="1"
                cp -f $DIR_APACHE_CONF/centreon.conf $DIR_APACHE_CONF/centreon.conf-bak >> $LOG_FILE 2>&1
                echo_info "$(gettext "Backup Centreon Apache configuration completed")"
            fi
        else
            yes_no_default "$(gettext "Do you want to add the Centreon Apache sub configuration file?")"
            [ "$?" -eq 0 ] && write_config="1"
        fi
    else
        write_config="1"
    fi
    if [ "$write_config" -eq 1 ] ; then
        if [ "$upgrade" -eq 1 ] ; then
            cp -f $dir_conf/centreon.apache.conf $DIR_APACHE_CONF/centreon.conf.new >> $LOG_FILE 2>&1
        else
            cp -f $dir_conf/centreon.apache.conf $DIR_APACHE_CONF/centreon.conf >> $LOG_FILE 2>&1
        fi
        echo_success "$(gettext "Create") '$DIR_APACHE_CONF/centreon.conf'" "$ok"
        echo_success "$(gettext "Configuring Apache")" "$ok"
        # After finishing the configuration ->
        # reload apache ! (if admin wants :p)
        if [ "${APACHE_RELOAD:-0}" -eq 0 ] ; then
            yes_no_default "$(gettext "Do you want to reload your Apache?")"
            [ $? -eq 0 ] && reload_service_apache
        elif [ "${APACHE_RELOAD:-0}" -eq 1 ] ; then
            reload_service_apache
        fi
    else
        echo_info "$(gettext "Please config Apache with this example"):\n $dir_conf/centreon.apache.conf"
    fi
}

#----
## Copy ssh keys to gorgone and add proper rights
#----
copy_ssh_keys_to_gorgone() {
    if [ ! -d "$GORGONE_VARLIB/.ssh" ] ; then
        mkdir -p "$GORGONE_VARLIB/.ssh"
        if [ $? -ne 0 ] ; then
            echo_failure "$(gettext "Cannot create the subfolder $GORGONE_VARLIB/.ssh")" "$fail"
            return 1
        fi
    fi

    if [ -z $CENTREON_SPOOL_SSH ] ; then
        echo_failure "$(gettext "Cannot find the '.ssh' folder in the $CENTREON_USER home folder")" "$fail"
        return 1
    fi

    cp -Rf "$CENTREON_SPOOL_SSH/.ssh" "$GORGONE_VARLIB"
    if [ $? -ne 0 ] ; then
        echo_failure "$(gettext "Cannot move the SSH keys to $GORGONE_VARLIB/.ssh")" "$fail"
        return 1
    fi

    ${CHOWN} -R "$GORGONE_USER:$GORGONE_GROUP" "$GORGONE_VARLIB/.ssh"
    if [ $? -ne 0 ] ; then
        echo_failure "$(gettext "Cannot modify the owner of the files in $GORGONE_VARLIB/.ssh folder to $GORGONE_USER:$GORGONE_GROUP")" "$fail"
        return 1
    fi

    ${CHMOD} 600 "$GORGONE_VARLIB/.ssh/id_rsa"
    if [ $? -ne 0 ] ; then
        echo_failure "$(gettext "Cannot modify the rights of files in folder $GORGONE_VARLIB/.ssh")" "$fail"
        return 1
    fi

    echo_success "$(gettext "Copy SSH keys to $GORGONE_VARLIB/.ssh")" "$ok"
    return 0
}

#----
## Create gorgone configuration folders
#----
create_gorgone_configuration_structure() {
    ## check the required gorgone configuration structure
    conf_folder="$GORGONE_CONFIG/config.d"
    if [ ! -d "$conf_folder" ] ; then
        echo_failure "$(gettext "Gorgone configuration folder is missing") $conf_folder" "$fail"
        echo_failure "$(gettext "Please reinstall Gorgone service")" "$fail"
        return 1
    fi

    # gorgone's config.d/30-centreon.yaml
    destination="$conf_folder/30-centreon.yaml"
    if [ -e $destination ] ; then
        yes_no_default "$(gettext "A configuration file already exists. Do you want to overwrite it?")"
        if [ $? -ne 0 ] ; then
            echo_info "$(gettext "If needed, please update") $destination" "$passed"
        else
            ${CAT} <<- __EOT__ > $destination
name: centreon.yaml
description: Configure Centreon Gorgone to work with Centreon Web.
centreon: !include $CENTREON_ETC/config.d/*.yaml
__EOT__

            echo_success "$(gettext "Create gorgone's 30-centreon.yaml file")" "$ok"
        fi
    fi

    ## create the required centreon configuration structure
    if [ ! -d "$CENTREON_ETC/config.d" ] ; then
        mkdir "$CENTREON_ETC/config.d"
        if [ $? -ne 0 ] ; then
            echo_failure "$(gettext "Cannot create the subfolder") $CENTREON_ETC/config.d" "$fail"
            return 1
        fi
    fi
    echo_success "$(gettext "Create centreon config folders")" "$ok"

    # centreon's config.yaml
    destination="$CENTREON_ETC/config.yaml"
    if [ -e $destination ] ; then
        yes_no_default "$(gettext "A configuration file already exists. Do you want to overwrite it?")"
        if [ $? -ne 0 ] ; then
            echo_info "$(gettext "If needed, please update") $destination" "$passed"
        else
            ${CAT} <<__EOT__ > $destination
name: config.yaml
description: Configuration for Central server
configuration: !include config.d/*.yaml
__EOT__

            echo_success "$(gettext "Create centreon config.yaml")" "$ok"
        fi
    fi
    echo_success "$(gettext "Gorgone configuration structure")" "$ok"
    return 0
}

#----
## Define apache service init script and ask to reload apache
## @return 0 	Apache reload OK
## @return 1	Apache reload FAIL
#----
reload_service_apache() {
    local service=""
    log "INFO" "$(gettext "Reloading Apache...")"
    if [ -x /etc/init.d/apache ] ; then
        service="apache"
    elif [ -x /etc/init.d/httpd ] ; then
        service="httpd"
    elif [ -x /bin/systemctl ] ; then
        if [ $(/bin/systemctl list-units | grep httpd24-httpd | wc -l) -gt "0" ] ; then
            service="httpd24-httpd"
        elif [ $(/bin/systemctl list-units | grep httpd | wc -l) -gt "0" ] ; then
            service="httpd"
        elif [ $(/bin/systemctl list-units | grep apache2 | wc -l) -gt "0" ] ; then
            service="apache2"
        fi
    elif [ -x /etc/init.d/apache2 ] ; then
        service="apache2"
    elif [ -x /usr/local/etc/rc.d/apache ] ; then
        service="apache"
    elif [ -x /usr/local/etc/rc.d/apache2 ]; then
        service="apache2"
    else
        echo_warning "$(gettext "Unable to reload Apache server")" "$warning"
    fi

    log "DEBUG" "$(gettext "use") : $service"
    # reload apache service
    $SERVICE_BINARY $service reload >> $LOG_FILE 2>&1
    if [ "$?" -eq 0 ] ; then
        echo_success "$(gettext "Reloading Apache service")" "$ok"
        return 0
    else
        echo_failure "$(gettext "Reloading Apache service")" "$fail"
        return 1
    fi
}

#----
## Prepare a file for apache config
## This function write a config in directory ($1)
## and test if that config exist.
## @param	directory to generate apache.conf
## @return 0	create file ok
## @return 1	create file fail
#----
prepare_apache_config() {
    local directory="$1"

    # if INSTALL_DIR_CENTREON not found, ask:
    [ -z "$INSTALL_DIR_CENTREON" ] && locate_centreon_installdir

    # Prepare apache config
    ${CAT} << __EOT__ > $directory/centreon.apache.conf
Define base_uri "/centreon"
Define install_dir "$INSTALL_DIR_CENTREON"

ServerTokens Prod

<VirtualHost *:80>
    Header set X-Frame-Options: "sameorigin"
    Header always edit Set-Cookie ^(.*)$ $1;HttpOnly;SameSite=Strict
    ServerSignature Off
    TraceEnable Off

    Alias ${base_uri}/api ${install_dir}
    Alias ${base_uri} ${install_dir}/www/

    <IfModule mod_brotli.c>
        AddOutputFilterByType BROTLI_COMPRESS text/html text/plain text/xml text/css text/javascript application/javascript application/json
    </IfModule>

    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript application/json

    <LocationMatch ^\${base_uri}/?(?!api/latest/|api/beta/|api/v[0-9]+/|api/v[0-9]+\.[0-9]+/)(.*\.php(/.*)?)$>
        ProxyPassMatch "fcgi://127.0.0.1:9042${install_dir}/www/$1"
    </LocationMatch>

    <LocationMatch ^\${base_uri}/?(authentication|api/(latest|beta|v[0-9]+|v[0-9]+\.[0-9]+))/.*$>
        ProxyPassMatch "fcgi://127.0.0.1:9042${install_dir}/api/index.php/$1"
    </LocationMatch>

    ProxyTimeout 300
    ErrorDocument 404 ${base_uri}/index.html
    Options -Indexes +FollowSymLinks

    <IfModule mod_security2.c>
        # https://github.com/SpiderLabs/ModSecurity/issues/652
        SecRuleRemoveById 200003
    </IfModule>

    <Directory "${install_dir}/www">
        DirectoryIndex index.php
        AllowOverride none
        Require all granted
        FallbackResource ${base_uri}/index.html
    </Directory>

    <Directory "${install_dir}/api">
        AllowOverride none
        Require all granted
    </Directory>

    <If "'${base_uri}' != '/'">
        RedirectMatch ^/$ ${base_uri}
    </If>
</VirtualHost>
__EOT__

    if [ -e $directory/centreon.apache.conf ] ; then
        return 0
    else
        log "INFO" "$(gettext "Problem when generating apache configuration")"
        return 1
    fi
}

#----
## Check PHP FPM configuration directory
## @Globals	DIR_PHP_FPM_CONF
#----
check_php_fpm_directory() {
    if [ -z "$DIR_PHP_FPM_CONF" ] ; then
        if [ -d /etc/php/8.0/fpm/pool.d ]; then
            DIR_PHP_FPM_CONF="/etc/php/8.0/fpm/pool.d"
        elif [ -d /etc/php-fpm.d ] ; then
            DIR_PHP_FPM_CONF="/etc/php-fpm.d"
        else
            echo_passed "$(gettext "PHP FPM config directory not found")" "$critical"
            answer_with_testdir "$(gettext "Where is your PHP FPM conf.d directory")" "NO_DEFAULT" "DIR_PHP_FPM_CONF"
        fi
    fi
    DIR_PHP_FPM_CONF=${DIR_PHP_FPM_CONF%/}
    export DIR_PHP_FPM_CONF
    log "INFO" "DIR_PHP_FPM_CONF: $DIR_PHP_FPM_CONF"

    return 0
}

#----
## Configure PHP FPM
## @Globals	silent_install, DIR_PHP_FPM_CONF, PHP_FPM_RELOAD
#----
configure_php_fpm() {
    echo -e "\n$line"
    echo -e "\t$(gettext "Configure PHP FPM service")"
    echo -e "$line"

    local write_config="0"
    local dir_conf="$1"
    # Generate a apache config in directory
    prepare_php_fpm_config "$dir_conf"

    if [ "$silent_install" -ne 1 ] ; then
        if [ -e $DIR_PHP_FPM_CONF/centreon.conf ] ; then
            echo "$(gettext "Finding PHP FPM Centreon configuration file")"
            echo_success "'$DIR_PHP_FPM_CONF/centreon.conf' :" "$ok"
            yes_no_default "$(gettext "Do you want to update Centreon PHP FPM sub configuration file?")"
            if [ "$?" -eq 0 ] ; then
                write_config="1"
                cp -f $DIR_PHP_FPM_CONF/centreon.conf $DIR_PHP_FPM_CONF/centreon.conf-bak >> $LOG_FILE 2>&1
                echo_info "$(gettext "Backup Centreon PHP FPM configuration completed")"
            fi
        else
            yes_no_default "$(gettext "Do you want to add the Centreon PHP FPM sub configuration file?")"
            [ "$?" -eq 0 ] && write_config="1"
        fi
    else
        write_config="1"
    fi

    if [ "$write_config" -eq 1 ] ; then
        dir_test_create "$CENTREON_VARLIB/sessions"
        if [ "$upgrade" -eq 1 ] ; then
            cp -f $dir_conf/centreon.php-fpm.conf $DIR_PHP_FPM_CONF/centreon.conf.new >> $LOG_FILE 2>&1
        else
            cp -f $dir_conf/centreon.php-fpm.conf $DIR_PHP_FPM_CONF/centreon.conf >> $LOG_FILE 2>&1
        fi
        echo_success "$(gettext "Create") '$DIR_PHP_FPM_CONF/centreon.conf'" "$ok"
        echo_success "$(gettext "Configuring PHP FPM")" "$ok"

        # Reload php-fpm ?
        if [ "${PHP_FPM_RELOAD:-0}" -eq 0 ] ; then
            yes_no_default "$(gettext "Do you want to reload PHP FPM service?")"
            [ $? -eq 0 ] && reload_service_php_fpm
        elif [ "${PHP_FPM_RELOAD:-0}" -eq 1 ] ; then
            reload_service_php_fpm
        fi
    else
        echo_info "$(gettext "Please configure PHP FPM with this example"):\n $dir_conf/centreon.php-fpm.conf"
    fi
}

#----
## Create configuration file of PHP FPM
## @Globals	INSTALL_DIR_CENTREON
#----
prepare_php_fpm_config() {
    local directory="$1"

    # if INSTALL_DIR_CENTREON not found, ask:
    [ -z "$INSTALL_DIR_CENTREON" ] && locate_centreon_installdir

    # Prepare apache config
    ${CAT} << __EOT__ > $directory/centreon.php-fpm.conf
[centreon]
user = $WEB_USER
group = $WEB_GROUP
listen = 127.0.0.1:9042
listen.allowed_clients = 127.0.0.1
pm = ondemand
pm.max_children = 30
pm.process_idle_timeout = 10s
pm.max_requests = 500
rlimit_files = 4096
php_admin_value[error_log] = $CENTREON_LOG/centreon-error.log
php_admin_flag[log_errors] = on
php_value[session.save_handler] = files
php_value[session.save_path]    = $CENTREON_VARLIB/sessions

__EOT__

    if [ -e $directory/centreon.php-fpm.conf ] ; then
        return 0
    else
        log "INFO" "$(gettext "Problem when generating PHP FPM configuration")"
        return 1
    fi
}

#----
## Reload PHP FPM service
#----
reload_service_php_fpm() {
    local service_reloaded=0
    log "INFO" "$(gettext "Reloading PHP FPM...")"
    if [ -x /bin/systemctl ] ; then
        local php_fpm_service=$(/bin/systemctl list-units | grep php | grep fpm | cut -f 1 -d " ")
        if [ ! -z "$php_fpm_service" ] ; then
            /bin/systemctl reload $php_fpm_service >> $LOG_FILE 2>&1
            if [ "$?" -eq 0 ] ; then
                echo_success "$(gettext "Reloading PHP FPM service")" "$ok"
                service_reloaded=1
            else
                echo_failure "$(gettext "Reloading PHP FPM service")" "$fail"
            fi
        fi
    fi

    if [ "$service_reloaded" -eq 0 ] ; then
        echo_warning "$(gettext "Unable to reload PHP FPM service")" "$warning"
    fi
}

#----
## Prepare Sudo config file
## This function write a config in directory ($1)
## <p>
## Call:<p>
##	- <@function locate_sudo><p>
## @param	directory to generate a centreon.sudo file
## @return 0	create file ok
## @return 1	create file fail
## @Globals	MONITORINGENGINE_BINARY, INIT_D, WEB_USER
#----
prepare_sudo_config() {
    local directory="$1"

    locate_sudo
    # find nagios binary if not define
    [ -z "$MONITORINGENGINE_BINARY" ] && answer_with_testfile "$(gettext "What is the Monitoring engine binary?") [$DEFAULT_MONITORINGENGINE_BINARY]" "$DEFAULT_MONITORINGENGINE_BINARY" "MONITORINGENGINE_BINARY"
    [ -z "$MONITORINGENGINE_ETC" ] && locate_monitoringengine_etc
    [ -z "$BROKER_ETC" ] && locate_broker_etc
    [ -z "$SERVICE_BINARY" ] && answer_with_testfile "$(gettext "Where is your service command binary?")" "$(which service)" "SERVICE_BINARY"
    # Prepare sudo.conf

	${CAT} <<- __EOT__ > $directory/centreon.sudo
## BEGIN: CENTREON SUDO

User_Alias      CENTREON=%$CENTREON_GROUP
Defaults:CENTREON !requiretty

# centreontrapd
CENTREON   ALL = NOPASSWD: $SERVICE_BINARY centreontrapd start
CENTREON   ALL = NOPASSWD: $SERVICE_BINARY centreontrapd stop
CENTREON   ALL = NOPASSWD: $SERVICE_BINARY centreontrapd restart
CENTREON   ALL = NOPASSWD: $SERVICE_BINARY centreontrapd reload

# Centreon Engine
CENTREON   ALL = NOPASSWD: $SERVICE_BINARY centengine start
CENTREON   ALL = NOPASSWD: $SERVICE_BINARY centengine stop
CENTREON   ALL = NOPASSWD: $SERVICE_BINARY centengine restart
CENTREON   ALL = NOPASSWD: $SERVICE_BINARY centengine reload
CENTREON   ALL = NOPASSWD: $MONITORINGENGINE_BINARY -v *

# Centreon Broker
CENTREON   ALL = NOPASSWD: $SERVICE_BINARY cbd start
CENTREON   ALL = NOPASSWD: $SERVICE_BINARY cbd stop
CENTREON   ALL = NOPASSWD: $SERVICE_BINARY cbd restart
CENTREON   ALL = NOPASSWD: $SERVICE_BINARY cbd reload

## END: CENTREON SUDO
__EOT__

    if [ -e $directory/centreon.sudo ] ; then
        return 0
    else
        log "INFO" "$(gettext "Problem when generating sudo configuration")"
        return 1
    fi
}

#----
## Find config problem on sudo
## If I found a problem, print a warning and need to press enter.
## @Globals	LOG_FILE
## @return 0	no problem in sudo file
## @return 1	possible problem in sudo file
#----
is_suspect_conf_sudo() {
    local sudo_file="$1"
    ${GREP} -e "^Defaults.*requiretty$" $sudo_file >> $LOG_FILE 2>&1
    if [ "$?" -eq 0 ] ; then
        echo_warning "$(gettext "I think you'll have a problem with\n'Default requiretty' in sudo file")"
        echo -e "$(gettext "Press enter to continue.")"
        read
        return 1
    fi
    return 0
}

#----
## Configure Sudo on system
## Need a directory to store a config
## Call <@function prepare_sudo_config>
## @param	Directory to store a Sudo config (generate)
## @Globals	SUDO_FILE, line
## @return 0	end
#----
configureSUDO() {
    echo -e "\n$line"
    echo -e "\t$(gettext "Configure Sudo")"
    echo -e "$line"
    local no_force_sudo="0"
    local dir_conf="$1"
    # Generate a sudo config in directory
    prepare_sudo_config "$dir_conf"

    # Try to detect old configuration
    sudo=`${GREP} -e "CENTREON SUDO" $SUDO_FILE > /dev/null 2>&1 ; echo $?`
    if [ $sudo -eq 1 ]; then
        echo_info "$(gettext "Your sudo is not configured")"

        if [ "${FORCE_SUDO_CONF:-0}" -eq 1 ] ; then
            no_force_sudo="0"
        else
            yes_no_default "$(gettext "Do you want to configure your sudo? (WARNING) ")"
            no_force_sudo="$?"
        fi
        if [ $no_force_sudo -eq 0 ] ; then
            ${CAT} $dir_conf/centreon.sudo >> $SUDO_FILE
            echo_success "$(gettext "Configuring Sudo")" "$ok"
        else
            echo_passed "$(gettext "Please configure your sudo with this example"):\n\t $dir_conf/centreon.sudo" "$passed"
        fi
    else
        echo_info "$(gettext "Your sudo has been configured previously")"
        if [ "${FORCE_SUDO_CONF:-0}" -eq 1 ] ; then
            no_force_sudo="0"
        else
            yes_no_default "$(gettext "Do you want to reconfigure your sudo? (WARNING) ")"
            no_force_sudo="$?"
        fi
        if [ $no_force_sudo -eq 0 ] ; then
            clean_sudo $SUDO_FILE 0
            ${CAT} $dir_conf/centreon.sudo >> $SUDO_FILE
            echo_success "$(gettext "Configuring Sudo")" "$ok"
        else
            echo_passed "$(gettext "Please configure your sudo with this example"):\n\t $dir_conf/centreon.sudo" "$passed"
        fi
    fi
    log "INFO" "$(gettext "Please configure your sudo using this example"): $dir_conf/centreon.sudo"
    return 0
}

#----
## Create a config file for Web post install
## @Globals	line, INSTALL_DIR_CENTREON, CENTREON_ETC,
## @Globals	MONITORINGENGINE_BINARY
## @Globals	BIN_RRDTOOL, WEB_USER, WEB_GROUP,
## @Globals	CENTREON_USER, BIN_MAIL
#----
createConfFile() {
    echo -e "\n$line"
    echo -e "\t\t$(gettext "Centreon Post Install")"
    echo -e "$line"

    INSTALL_DIR_CENTREON_CONF="$INSTALL_DIR_CENTREON/www/install/install.conf.php"
    # Reinit file if exist
    touch $INSTALL_DIR_CENTREON_CONF
	${CAT} << __EOT__ > $INSTALL_DIR_CENTREON_CONF
<?php

/*
 * Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * For more information : contact@centreon.com
 *
 */

\$conf_centreon['centreon_dir'] = "$INSTALL_DIR_CENTREON/";
\$conf_centreon['centreon_etc'] = "$CENTREON_ETC/";
\$conf_centreon['centreon_dir_www'] = "$INSTALL_DIR_CENTREON/www/";
\$conf_centreon['centreon_dir_rrd'] = "$INSTALL_DIR_CENTREON/rrd/";
\$conf_centreon['centreon_log'] = "$CENTREON_LOG";
\$conf_centreon['centreon_cachedir'] = "$CENTREON_CACHEDIR";
\$conf_centreon['centreon_varlib'] = "$CENTREON_VARLIB";
\$conf_centreon['centreon_group'] = "$CENTREON_GROUP";
\$conf_centreon['centreon_user'] = "$CENTREON_USER";
\$conf_centreon['rrdtool_dir'] = "$BIN_RRDTOOL";
\$conf_centreon['apache_user'] = "$WEB_USER";
\$conf_centreon['apache_group'] = "$WEB_GROUP";
\$conf_centreon['mail'] = "$BIN_MAIL";
\$conf_centreon['broker_user'] = "$BROKER_USER";
\$conf_centreon['broker_group'] = "$BROKER_GROUP";
\$conf_centreon['broker_etc'] = "$BROKER_ETC";
\$conf_centreon['monitoring_user'] = "$MONITORINGENGINE_USER";
\$conf_centreon['monitoring_group'] = "$MONITORINGENGINE_GROUP";
\$conf_centreon['monitoring_etc'] = "$MONITORINGENGINE_ETC";
\$conf_centreon['monitoring_binary'] = "$MONITORINGENGINE_BINARY";
\$conf_centreon['monitoring_varlog'] = "$MONITORINGENGINE_LOG";
\$conf_centreon['plugin_dir'] = "$PLUGIN_DIR";
\$conf_centreon['centreon_engine_connectors'] = "$CENTREON_ENGINE_CONNECTORS";
\$conf_centreon['centreon_plugins'] = "$CENTREON_PLUGINS";

__EOT__

    echo "?>" >> $INSTALL_DIR_CENTREON_CONF
    log "INFO" "$(gettext "Change rights on") : $INSTALL_DIR_CENTREON_CONF"
    ${CHOWN} $WEB_USER:$WEB_GROUP $INSTALL_DIR_CENTREON_CONF >> $LOG_FILE 2>&1
    echo_success "Create $INSTALL_DIR_CENTREON_CONF" "OK"
}

#----
## Create a config file for CentWeb
## Create a config file with all used variables.
## This file will use in upgrade progess.
## @Globals	CENTREON_ETC, INSTALL_DIR_CENTREON, INSTALL_DIR_NAGIOS,
## @Globals	NAGIOS_ETC, NAGIOS_USER, INIT_D, DIR_APACHE, NAGIOS_P1_FILE
## @Globals	NAGIOS_PLUGIN, NAGIOS_IMG, NAGIOS_BINARY, NAGIOSTATS_BINARY,
## @Globals	NAGIOS_VAR, SUDO_FILE, WEB_USER, WEB_GROUP,
## @Globals	NAGIOS_GROUP, BIN_RRDTOOL, BIN_MAIL, PEAR_PATH, CENTREON_LOG,
## @Globals	CENTREON_ETC, CENTREON_CACHEDIR, CRON_D, NDOMOD_BINARY
#----
createCentreonInstallConf() {
	${CAT} <<- __EOT__ > $CENTREON_ETC/instCentWeb.conf
	INSTALL_DIR_CENTREON=$INSTALL_DIR_CENTREON
	SUDO_FILE=$SUDO_FILE
	WEB_USER=$WEB_USER
	WEB_GROUP=$WEB_GROUP
	BIN_RRDTOOL=$BIN_RRDTOOL
	BIN_MAIL=$BIN_MAIL
	PEAR_PATH=$PEAR_PATH
	CENTREON_LOG=$CENTREON_LOG
	CENTREON_ETC=$CENTREON_ETC
	CENTREON_BINDIR=$CENTREON_BINDIR
	CENTREON_CACHEDIR=$CENTREON_CACHEDIR
	CENTREON_VARLIB=$CENTREON_VARLIB
	CENTREON_GROUP=$CENTREON_GROUP
	CENTREON_USER=$CENTREON_USER
	CRON_D=$CRON_D
	INIT_D=$INIT_D
	PHP_BIN=$PHP_BIN
	DIR_APACHE=$DIR_APACHE
	DIR_APACHE_CONF=$DIR_APACHE_CONF
	CENTPLUGINSTRAPS_BINDIR=$CENTPLUGINSTRAPS_BINDIR
	BROKER_ETC=$BROKER_ETC
	BROKER_USER=$BROKER_USER
	MONITORINGENGINE_ETC=$MONITORINGENGINE_ETC
	MONITORINGENGINE_BINARY=$MONITORINGENGINE_BINARY
	MONITORINGENGINE_LOG=$MONITORINGENGINE_LOG
	MONITORINGENGINE_USER=$MONITORINGENGINE_USER
	PLUGIN_DIR=$PLUGIN_DIR
	CENTREON_PLUGINS=$CENTREON_PLUGINS
	__EOT__

    echo_success "Create $CENTREON_ETC/instCentWeb.conf " "OK"
    return 0
}

#---
## Create a config file for CentStorage
## This file will use for upgrade process
## @Globals	CENTREON_ETC, INSTALL_DIR_CENTREON, CENTREON_LOG, CENTREON_ETC
## @Globals	CENTREON_RUNDIR, CENTSTORAGE_RRD, CENTSTORAGE_BINDIR
## @Globals	NAGIOS_USER, NAGIOS_GROUP, CRON_D, INIT_D
#----
createCentStorageInstallConf() {
	${CAT} <<- __EOT__ > $CENTREON_ETC/instCentStorage.conf
	INSTALL_DIR_CENTREON=$INSTALL_DIR_CENTREON
	CENTREON_LOG=$CENTREON_LOG
	CENTREON_ETC=$CENTREON_ETC
	CENTREON_RUNDIR=$CENTREON_RUNDIR
	CENTREON_CACHEDIR=$CENTREON_CACHEDIR
	CENTREON_VARLIB=$CENTREON_VARLIB
	NAGIOS_VAR=$NAGIOS_VAR
	INIT_D=$INIT_D
	CRON_D=$CRON_D
	CENTSTORAGE_BINDIR=$CENTSTORAGE_BINDIR
	CENTSTORAGE_RRD=$CENTSTORAGE_RRD
	CENTREON_USER=$CENTREON_USER
	CENTREON_GROUP=$CENTREON_GROUP
	__EOT__

    echo_success "Create $CENTREON_ETC/instCentStorage.conf " "OK"
    return 0
}

#---
## Create a config file for CentPlugins
## This file will use for upgrade process
## @Globals	CENTREON_ETC, NAGIOS_PLUGIN, INSTALL_DIR_NAGIOS, NAGIOS_ETC
## @Globals	CENTPLUGINS_TMP, NAGIOS_USER, NAGIOS_GROUP, INIT_D
## @Globals	SNMP_ETC, SNMPTT_BINDIR, CENTPLUGINSTRAPS_BINDIR, WEB_USER
#----
createCentPluginsInstallConf() {
	${CAT} <<- __EOT__ > $CENTREON_ETC/instCentPlugins.conf
	# Use in CentPlugins.sh
	PLUGIN_DIR=$PLUGIN_DIR
	CENTREON_PLUGINS=$CENTREON_PLUGINS
	INSTALL_DIR_NAGIOS=$INSTALL_DIR_NAGIOS
	INSTALL_DIR_CENTREON=$INSTALL_DIR_CENTREON
	NAGIOS_ETC=$NAGIOS_ETC
	CENTPLUGINS_TMP=$CENTPLUGINS_TMP
	CENTREON_USER=$CENTREON_USER
	CENTREON_GROUP=$CENTREON_GROUP
	INIT_D=$INIT_D
	CENTREON_ETC=$CENTREON_ETC
	MONITORINGENGINE_ETC=$MONITORINGENGINE_ETC
	MONITORINGENGINE_LOG=$MONITORINGENGINE_LOG
	MONITORINGENGINE_GROUP=$MONITORINGENGINE_GROUP
	MONITORINGENGINE_USER=$MONITORINGENGINE_USER
	__EOT__

    echo_success "Create $CENTREON_ETC/instCentPlugins.conf " "OK"
    return 0
}

#---
## Create a config file for CentPlugins
## This file will use for upgrade process
## @Globals	CENTREON_ETC, NAGIOS_PLUGIN, INSTALL_DIR_NAGIOS, NAGIOS_ETC
## @Globals	CENTPLUGINS_TMP, NAGIOS_USER, NAGIOS_GROUP, INIT_D
## @Globals	SNMP_ETC, SNMPTT_BINDIR, CENTPLUGINSTRAPS_BINDIR, WEB_USER
#----
createCentPluginsForTrapdInstallConf() {
	${CAT} <<- __EOT__ >>  $CENTREON_ETC/instCentPlugins.conf
	# Use in CentPluginsTraps.sh
	SNMP_ETC=$SNMP_ETC
	CENTREONTRAPD_BINDIR=$CENTREONTRAPD_BINDIR
	CENTPLUGINSTRAPS_BINDIR=$CENTPLUGINSTRAPS_BINDIR
	WEB_USER=$WEB_USER
	CENTREON_USER=$CENTREON_USER
	CENTREON_GROUP=$CENTREON_GROUP
	CENTREON_RUNDIR=$CENTREON_RUNDIR
	CENTREON_ETC=$CENTREON_ETC
	CENTREON_LOG=$CENTREON_LOG
	__EOT__

    echo_success "Create $CENTREON_ETC/instCentPlugins.conf " "OK"
    return 0
}

#----
## Define where is Apache config directory
## @return 0
## @Globals	DIR_APACHE, DIR_APACHE_CONF, APACHE_CONF
#----
check_httpd_directory() {
    if [ -z "$DIR_APACHE" -o -z "$DIR_APACHE_CONF" ] ; then
        if [ -d /opt/rh/httpd24/root/etc/httpd/conf ] ; then
            DIR_APACHE="/opt/rh/httpd24/root/etc/httpd/conf"
            DIR_APACHE_CONF="/opt/rh/httpd24/root/etc/httpd/conf.d"
        elif [ -d /etc/apache/conf ] ; then
            DIR_APACHE="/etc/apache/conf"
            DIR_APACHE_CONF="/etc/apache/conf.d"
        elif [ -d /usr/local/apache2/conf ] ; then
            DIR_APACHE="/usr/local/apache2/conf"
            DIR_APACHE_CONF="/usr/local/apache2/conf"
        elif [ -d /etc/apache2 ] ; then
            DIR_APACHE="/etc/apache2"
            DIR_APACHE_CONF="/etc/apache2/conf-available"
            if [ -d '/etc/apache2/conf-avaible' ] ; then
                DIR_APACHE_CONF="/etc/apache2/conf-available"
            elif [ -d '/etc/apache2/conf.d' ] ; then
                DIR_APACHE_CONF="/etc/apache2/conf.d"
            fi
            if [ ! -d "$DIR_APACHE_CONF" ] ; then
                mkdir "$DIR_APACHE_CONF"
                echo_success "$(gettext "Created Apache configuration directory")" "$ok"
            fi
            if [ -d '/etc/apache2/conf-enabled' -a -x "$(type -p a2enconf 2>/dev/null)" ] ; then
                echo_success "$(gettext "Enable Apache configuration")" "$ok"
                a2enconf centreon.conf
            fi
        elif [ -d /etc/httpd/conf ] ; then
            DIR_APACHE="/etc/httpd/conf"
            DIR_APACHE_CONF="/etc/httpd/conf.d"
        elif [ -d /usr/local/etc/apache ] ; then
            DIR_APACHE="/usr/local/etc/apache"
            DIR_APACHE_CONF="/usr/local/etc/apache/Includes"
        elif [ -d /usr/local/etc/apache2 ] ; then
            DIR_APACHE="/usr/local/etc/apache2"
            DIR_APACHE_CONF="/usr/local/etc/apache2/Includes"
        elif [ -d /usr/local/etc/apache22 ] ; then
            # add for freeBSD 7 with apache2.2
            DIR_APACHE="/usr/local/etc/apache22"
            DIR_APACHE_CONF="/usr/local/etc/apache22/Includes"
        else
            echo_passed "$(gettext "Apache config directoty not found")" "$critical"
            answer_with_testdir "$(gettext "Where is your Apache etc directory")" "NO_DEFAULT" "DIR_APACHE"
            answer_with_testdir "$(gettext "Where is your Apache conf.d directory")" "NO_DEFAULT" "DIR_APACHE_CONF"
        fi
    fi
    DIR_APACHE=${DIR_APACHE%/}
    export DIR_APACHE
    DIR_APACHE_CONF=${DIR_APACHE_CONF%/}
    export DIR_APACHE_CONF
    log "INFO" "DIR_APACHE: $DIR_APACHE"
    log "INFO" "DIR_APACHE_CONF: $DIR_APACHE_CONF"

    if [ -z "$APACHE_CONF" ] ; then
        if [ -e $DIR_APACHE/apache2.conf ] ; then
            APACHE_CONF="apache2.conf"
        elif [ -e $DIR_APACHE/apache.conf ] ; then
            APACHE_CONF="apache.conf"
        elif [ -e $DIR_APACHE/commondhttpd.conf ] ; then
            APACHE_CONF="commondhttpd.conf"
        elif [ -e $DIR_APACHE/httpd.conf ] ; then
            APACHE_CONF="httpd.conf"
        else
            echo_passed "$(gettext "Apache config file not found")" "$critical"
            answer_with_testfile "$(gettext "Where is your Apache config file")" "NO_DEFAULT" "APACHE_CONF"
        fi
    fi
    APACHE_CONF=${APACHE_CONF%/}
    export APACHE_CONF
    log "INFO" "APACHE_CONF: $APACHE_CONF"
    return 0
}

#----
## Find Apache user
## @Globals	WEB_USER, DIR_APACHE, APACHE_CONF
#----
check_user_apache() {
    # init WEB_USER if not define
    WEB_USER="$WEB_USER"

    if [ -n "$WEB_USER" ] ; then
        echo_info "$(gettext "Finding Apache user") :" "$WEB_USER"
        return 0
    fi
    local found=0
    if [ -e /etc/apache2/envvars ] ; then
        log "INFO" "$(gettext "Use envvars file for apache user")"
        # for Debian system (lenny)
        WEB_USER=`${CAT} /etc/apache2/envvars |${GREP} "USER" | cut -d= -f2`
        if [ -z "$WEB_USER" ] ; then
            found=0
        else
            found=1
        fi
    elif [ -e /etc/apache2/uid.conf ] ; then
        log "INFO" "$(gettext "Use uid.conf file for apache user")"
        # for SuSe system
        WEB_USER=`${CAT} /etc/apache2/uid.conf |${GREP} -e "^User" | cut -d" " -f2`
        if [ -z "$WEB_USER" ] ; then
            found=0
        else
            found=1
        fi
    fi
    if [ "$found" -eq 0 ] ; then
        WEB_USER=`${CAT} $DIR_APACHE/$APACHE_CONF | ${GREP} -e "^User" | cut -d" " -f2`
        if [ -z "$WEB_USER"  ] ; then
            local WEB_USER_TEMP=""
            for fichier in $DIR_APACHE/*
            do
                if [ -f "$fichier" ] ; then
                    log "INFO" "$(gettext "check apache user in") : $fichier"
                    WEB_USER_TEMP=`${CAT} $fichier | ${GREP} -e "^User" | cut -d" " -f2`
                    if [ -n "$WEB_USER_TEMP" ] ; then
                        log "INFO" "$(gettext "found apache user in") : $fichier"
                        WEB_USER=$WEB_USER_TEMP
                    fi
                fi
            done
        fi
    fi
    echo_info "$(gettext "Finding Apache user") :" "$WEB_USER"
    return 0
}

#----
## Find Apache group
## @Globals	WEB_GROUP, DIR_APACHE, APACHE_CONF
#----
check_group_apache() {
    # init WEB_GROUP if not define
    WEB_GROUP="$WEB_GROUP"

    if [ -n "$WEB_GROUP" ] ; then
        echo_info "$(gettext "Finding Apache group") :" "$WEB_GROUP"
        return 0
    fi
    local found=0
    if [ -e /etc/apache2/envvars ] ; then
        # for debian system
        WEB_GROUP=`${CAT} /etc/apache2/envvars |${GREP} "GROUP" |cut -d= -f2`
        if [ -z "$WEB_GROUP" ] ; then
            found=0
        else
            found=1
        fi
    elif [ -e /etc/apache2/uid.conf ] ; then
        # for SuSe system
        WEB_GROUP=`${CAT} /etc/apache2/uid.conf |${GREP} -e "^Group" | cut -d" " -f2`
        if [ -z "$WEB_GROUP" ] ; then
            found=0
        else
            found=1
        fi
    fi
    if [ "$found" -eq 0 ] ; then
        WEB_GROUP=`${CAT} $DIR_APACHE/$APACHE_CONF | ${GREP} -e "^Group" | cut -d" " -f2`
        if [  -z "$WEB_GROUP"  ] ; then
            local WEB_GROUP_TMP=""
            for fichier in $DIR_APACHE/*
            do
                if [ -f "$fichier" ];	then
                    WEB_GROUP_TEMP=`${CAT} $fichier | ${GREP} -e "^Group" | cut -d" " -f2`
                    if [ -n "$WEB_GROUP_TEMP" ]; then
                        WEB_GROUP=$WEB_GROUP_TEMP
                    fi
                fi
            done
        fi
    fi
    echo_info "$(gettext "Finding Apache group") :" "$WEB_GROUP"
    return 0
}

#----
## Ask for centreon user
## @Globals	CENTREON_USER, DEFAULT_CENTREON_USER
#----
check_centreon_user() {
    local groups="$CENTREON_GROUP"
    local description="Centreon Web user"
    local home="$CENTREON_VARLIB"
    if [ -n "$CENTREON_USER" ] ; then
        user_test "$CENTREON_USER"
        if [ $? -ne 0 ] ; then
            user_create "$CENTREON_USER" "$groups" "$description" "$home"
            if [ $? -ne 0 ] ; then
                CENTREON_USER=""
            fi
        fi
    fi
    if [ -z "$CENTREON_USER" ] ; then
        answer_with_createuser "$(gettext "What is the Centreon user?") [$DEFAULT_CENTREON_USER]" "$DEFAULT_CENTREON_USER" "CENTREON_USER" "$groups" "$description" "$home"
    fi
    log "INFO" "$(gettext "Centreon user") : $CENTREON_USER"
    return 0
}

#----
## Ask for centreon user, and create it if not exists
## @Globals	CENTREON_GROUP, DEFAULT_CENTREON_GROUP
#----
check_centreon_group() {
    if [ -n "$CENTREON_GROUP" ] ; then
        group_test "$CENTREON_GROUP"
        if [ $? -ne 0 ] ; then
            group_create "$CENTREON_GROUP"
            if [ $? -ne 0 ] ; then
                CENTREON_GROUP=""
            fi
        fi
    fi
    if [ -z "$CENTREON_GROUP" ] ; then
        answer_with_creategroup "$(gettext "What is the Centreon group?") [$DEFAULT_CENTREON_GROUP]" "$DEFAULT_CENTREON_GROUP" "CENTREON_GROUP"
    fi
    log "INFO" "$(gettext "Centreon group") : $CENTREON_GROUP"
    return 0
}

#----
## Ask for Centreon Engine user.
## @Globals	MONITORINGENGINE_USER
#----
check_engine_user() {
    if [ -z "${MONITORINGENGINE_USER}" ]; then
        answer_with_testuser "$(gettext "What is the Monitoring engine user?") [$DEFAULT_MONITORINGENGINE_USER]" "$DEFAULT_MONITORINGENGINE_USER" "MONITORINGENGINE_USER"
    fi
    log "INFO" "$(gettext "Monitoring engine user") : $MONITORINGENGINE_USER"
    return 0
}

#----
## Ask for Centreon Broker user.
## @Globals	BROKER_USER
#----
check_broker_user() {
    if [ -z "${BROKER_USER}" ]; then
        answer_with_testuser "$(gettext "What is the Broker user?") [$DEFAULT_BROKER_USER]" "$DEFAULT_BROKER_USER" "BROKER_USER"
    fi
    log "INFO" "$(gettext "Broker user") : $BROKER_USER"
    return 0
}


#----
## Ask for gorgone user
## @Globals	GORGONE_USER, DEFAULT_GORGONE_USER
#----
check_gorgone_user() {
    local groups="$GORGONE_GROUP"
    local description="Centreon Gorgone user"
    if [ -n "$GORGONE_USER" ] ; then
        user_test "$GORGONE_USER"
    fi
    if [ -z "$GORGONE_USER" ] ; then
        answer_with_testuser "$(gettext "What is the Gorgone user?") [$DEFAULT_GORGONE_USER]" "$DEFAULT_GORGONE_USER" "GORGONE_USER"
    fi
    log "INFO" "$(gettext "Gorgone user") : $GORGONE_USER"
    return 0
}

#----
## Ask for gorgone group, and create it if not exists
## @Globals	GORGONE_GROUP, DEFAULT_GORGONE_GROUP
#----
check_gorgone_group() {
    if [ -n "$GORGONE_GROUP" ] ; then
        group_test "$GORGONE_GROUP"
        if [ $? -ne 0 ] ; then
            group_create "$GORGONE_GROUP"
            if [ $? -ne 0 ] ; then
                GORGONE_GROUP=""
            fi
        fi
    fi
    if [ -z "$GORGONE_GROUP" ] ; then
        answer_with_creategroup "$(gettext "What is the Gorgone group?") [$DEFAULT_GORGONE_GROUP]" "$DEFAULT_GORGONE_GROUP" "GORGONE_GROUP"
    fi
    log "INFO" "$(gettext "Centreon group") : $GORGONE_GROUP"
    return 0
}

#----
## Copy Source directory on temporary working directory
## Copy Source directory and prepare work and final
## @Globals	TMP_DIR
#----
copyInTempFile() {
    local srclistcp="bin cron config logrotate GPL_LIB lang lib snmptrapd src vendor www api libinstall .env .env.local.php bootstrap.php container.php composer.json package.json pnpm-lock.yaml pnpm-workspace.yaml"
    # Prepare centreon Plugins
    echo "$(gettext "Preparing Centreon temporary files")"
    if [ -d $TMP_DIR ] ; then
        echo_passed "$TMP_DIR $(gettext "exists, it will be moved...")"
        mv $TMP_DIR $TMP_DIR.`date +%Y%m%d-%k%m%S`
    fi
    mkdir -p "$TMP_DIR/src"
    mkdir -p "$TMP_DIR/work"
    mkdir -p "$TMP_DIR/final"

    for folder in $srclistcp ; do
        log "INFO" "$(gettext "Copy") $BASE_DIR/$folder $(gettext "to") $TMP_DIR/src/"
        cp -Rf $BASE_DIR/$folder $TMP_DIR/src/
    done
}

#----
## use php script to check pear module
## @param	list of pear modules
## @return	return code of php script
## @Globals	PHP_BIN, INSTALL_DIR
#----
check_pear_module() {
    local module_list=$1
    echo -e "$(gettext "Check PEAR modules")"
    $PHP_BIN $INSTALL_DIR/check_pear.php check $module_list
    return "$?"
}

#----
## use php script to install missed pear module
## @param	list of pear modules
## @return	return code of php script
## @Globals	PHP_BIN, INSTALL_DIR
#----
install_pear_module() {
    local module_list=$1
    echo -e "$(gettext "Installing PEAR modules")"
    $PHP_BIN $INSTALL_DIR/check_pear.php install $module_list
    return "$?"
}

#----
## use php script to upgrade pear module
## @param	list of pear modules
## @return	return code of php script
## @Globals	PHP_BIN, INSTALL_DIR
#----
upgrade_pear_module() {
    local module_list=$1
    echo -e "$(gettext "Upgrading PEAR modules")"
    $PHP_BIN $INSTALL_DIR/check_pear.php upgrade $module_list
    return "$?"
}

#----
## install init script on distrib
## use this fonction to install a init script on your system
## it call <@function find_OS> to define install command
## @param	name of service
## @return 0	install service ok
## @return 1	install service fail
#----
install_init_service() {
	# how to find methode to install in rc.d directory a correct link ?
	# debian	update-rc.d
	# redhat	chkconfig
	# Suse		chkconfig
	# FreeBSD	add ${service}_enable=YES in /etc/rc.conf
    local service=$1
    OS=""
    find_OS "OS"
    if [ "$OS" = "DEBIAN" ] ; then
        chkconfig --add $service
    elif [ "$OS" = "SUSE" ] ; then
        chkconfig --add $service
    elif [ "$OS" = "REDHAT" ] ; then
        # Just for CentOS :p bug #1148
        if [ -x /sbin/chkconfig ] ; then
            /sbin/chkconfig --add $service
        else
            chkconfig --add $service
       fi
    elif [ "$OS" = "FREEBSD" ] ; then
        echo_info "$(gettext "You must configure your /etc/rc.conf with"): ${service}_enable=YES"
    else
        echo_passed "$(gettext "Impossible to install your run level for ") $service" "$fail"
        return 1
    fi
    return 0
}

#----
## Define OS
## check on etc to find a specific file <p>
## Debian, Suse, Redhat, FreeBSD
## @param	variable to set a result
#----
find_OS() {
    local distrib=$1
    local dist_found=""

    # From https://unix.stackexchange.com/questions/6345/how-can-i-get-distribution-name-and-version-number-in-a-simple-shell-script
    if [ -f /etc/os-release ]; then
        # freedesktop.org and systemd
        . /etc/os-release
        dist_found=${ID}
    elif type lsb_release >/dev/null 2>&1; then
        # linuxbase.org
        dist_found=$(lsb_release -si | sed -e 's/\(.*\)/\L\1/')
    elif [ -f /etc/lsb-release ]; then
        # For some versions of Debian/Ubuntu without lsb_release command
        . /etc/lsb-release
        dist_found=${DISTRIB_ID}
    elif [ -f /etc/debian_version ]; then
        # Older Debian/Ubuntu/etc.
        dist_found=debian
    elif [ -f /etc/centos-release ]; then
        # CentOS
        dist_found=centos
    elif [ -f /etc/redhat-release ]; then
        # Older Red Hat, CentOS, etc.
        dist_found=centos
    else
        # Fall back to uname, e.g. "Linux <version>", also works for BSD, etc.
        dist_found=$(uname -s)
    fi

    dist_found=$(echo $dist_found | tr [:lower:] [:upper:])

    log "INFO" "Distribution found: $dist_found"

    eval $distrib=$dist_found
}

#----
## use this function to clean and exit centreon install
## This function use <@function purge_centreon_tmp_dir> function.
## TODO: Need to add functionality
##      - delete install file
##      - restore inital rigth
##      - ...
#----
clean_and_exit() {
    local trap_sig=${1:-0}
    if [ $trap_sig -eq 0 ] ; then
        echo -e "$(gettext "\nTrap interrupt, Centreon'll exit now and clean install")"
        yes_no_default "$(gettext "Do you really want to quit the Centreon install process? ")" "$no"
        if [ $? -eq 1 ] ; then
            echo "$(gettext "Continue...")"
            return 1
        fi
    fi
    log "EXIT" "$(gettext "Exit Centreon install")"
    [ -n "$SUDO_FILE" -a $upgrade -eq 0 ] && clean_sudo "$SUDO_FILE" 0
    purge_centreon_tmp_dir "silent"
    exit 1
}

#----
## Check space left for working directory
## @return 0	Space ok
## @return 1	No Space left
## @Globals	TMP_DIR
#----
check_tmp_disk_space() {
    local min_space="35584"
    local free_space=""
    local tmp_dir=""

    tmp_dir=$(dirname $TMP_DIR)

    free_space=$(df -P $tmp_dir | tail -1 | awk '{print $4}')

    if [ "$free_space" -lt "$min_space" ] ; then
        echo_failure "$(gettext "No space left on tmp dir") : $tmp_dir  (<$min_space Ko)" "$fail"
        return 1
    else
        return 0
    fi
}

#----
## Ask to remove all temporaries working directory
## @param     silent option (silent)
## @return 0	remove done
## @return 1	don't remove (abort by user)
## @Globals	TMP_DIR, yes
#----
purge_centreon_tmp_dir() {
    local silent="$1"
    local not_clean="1"
    local rc="0"
    while [ $not_clean -ne 0 ] ; do
        if [ "$silent" != "silent" ] ; then
            yes_no_default "$(gettext "Do you want to remove the centreon temporary working space to continue installation?")" "$yes"
            rc=$?
        else
            rc=0
        fi
        if [ $rc -eq 0 ] ; then
            local tmp_base_dir=`dirname $TMP_DIR`
            local tmp_dir=`basename $TMP_DIR`
            find $tmp_base_dir -name "$tmp_dir*" -type d \
                -exec rm -rf {} \; 2>/dev/null
            not_clean="0"
        else
            return 1
        fi
    done
    return 0
}

#----
## Clean sudoers file
## Generate a file without Centreon config. Need to have a BEGIN and END flags
## file. After that, rewrite sudo file with clean file.
## @param	sudo file
## @param	0/1 to active a question to clean sudo (not by default)
## @Globals	TMP_DIR, LOG_FILE
#----
clean_sudo() {
    local RC="1"
    local sudo_old="$1"
    local validate="${2:-0}"
  if [ ! -d "$TMP_DIR" ] ; then
    local sudo_clean="/tmp/sudo.clean"
  else
      local sudo_clean="$TMP_DIR/sudo.clean"
  fi

  if ! grep "CENTREON SUDO" $sudo_old &>/dev/null ; then
    return 1
  fi

    ${CAT} $sudo_old | \
    awk 'BEGIN { flag=0; }
    /^## BEGIN: CENTREON SUDO/ { flag=1; next; }
    /^## END: CENTREON SUDO/ { flag=0; next; }
    { if (flag == 0) { print $0; } next; }' > $sudo_clean

    log "INFO" "$(gettext "New sudo file generate in:") $sudo_clean"
    if [ "$validate" -eq 1 ] ; then
        yes_no_default "$(gettext "Do you want to clean your sudo files? (clean centreon config)")"
        RC="$?"
    fi
    if [ "$RC" -eq 0 -o "$validate" -eq 0 ] ; then
        ${CAT} $sudo_clean > $sudo_old 2>$LOG_FILE
        return 0
    fi
    return 0
}

#----
## Find file with macro in directory.
## @param	macro (separate with comma)
## @param 	folder where to find
## @param	sub directory to find
## @param	file to search (possible to use pattern)
## @param	variable where define a list of file (temporary file)
## @Globals	LOG_FILE, TMP_DIR
#----
find_macros_in_dir() {
    local macro="$1"
    local src_dir="$2"
    local sub_dir="$3"
    local file="$4"
    local var_ref="$5"
    local file_out_tmp=""
    file_out_tmp=$(mktemp $TMP_DIR/file_out_tmp.XXXXXX)

    for mac in ${macro//,/ } ; do
        log "INFO" "$(gettext "Search file for macro") : $mac"
        ( cd $src_dir ;
            find $sub_dir -mindepth 1 -type f -name "$file" | \
                xargs ${GREP} -l "$mac" | \
                uniq >> "$file_out_tmp" 2>>"$LOG_FILE";
        )
    done

    eval $var_ref=$file_out_tmp
    return 0
}


#----
## Check result and print a message
## @param	return code to check
## @param	message to print
#----
check_result() {
    local code=$1
    shift
    local message=$@

    if [ $code -eq 0 ] ; then
        echo_success "$message" "$ok"
    else
        echo_failure "$message" "$fail"
    fi
    return 0
}

#----
## Add a group to a user
## @param	user name
## @param	group name
## @Globals	fail
## @return 0 	 end
## @return 1 	 fail
#----
add_group() {
    local user=$1
    local group=$2
    if [ -z "$user" -o -z "$group" ]; then
        echo_failure "$(gettext "Could not add group $group to user $user")" "$fail"
        return 1
    fi
    usermod -a -G $group $user &>/dev/null
    local ret=$?
    check_result $ret "$(gettext "Add group $group to user $user")"
    return $ret
}

#----
## Get the primary group of a user
## @param	user name
## @param	variable to set a result
## @return 1	fail
## @return 0	end
#----
get_primary_group() {
    local user=$1
    local var_ref=$2
    local group_name=$(id -ng "$user" 2>/dev/null)
    if [ -z "$group_name" ]; then
        return 1
    fi
    eval $var_ref=$group_name
    return 0
}

check_rrd_right() {
    if [ -d "${CENTSTORAGE_RRD}" ]; then
        ${CHOWN} -R ${CENTREON_USER}:${CENTREON_GROUP} "${CENTSTORAGE_RRD}"
        ${CHMOD} -R g+w "${CENTSTORAGE_RRD}"
    fi
}
