#!/usr/bin/env bash

#----
## @Synopsis	This file contains functions to be used by Centreon install scripts
## @Copyright	Copyright 2008, Guillaume Watteeux
## @Licence	GPLv2
## This file contains functions to be used by Centreon install scripts
#----

#################################
# SVN: $Id$

# 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
#----
function 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
#----
function 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
#----
function 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
#----
function 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
#----
function 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
#----
function 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
#----
function 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
#----
function 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
#----
function 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
#----
function 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
#----
function 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
#----
function 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
#----
function 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 "$(gettext "$res 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 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
#----
function 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 select slash...")"
			res="not_define"
		else
			first=1
			[ -d "$res" ] && break
			yes_no_default "$(gettext "Do you want me 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
#----
function 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 select slash...")"
                        res="not_define"
                else
                        first=1
                        [ -f "$res" ] && break
                        yes_no_default "$(gettext "Do you want me to create this file ?") [$res]"
                        if [ $? -eq 0 ] ; then
                                touch $res
                                if [ $? -ne 0 ] ; then
                                        echo_passed "$(gettext "Could not create 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
#----
function 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
#----
function 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 me 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
#----
function 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 me 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
#----
function 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
#----
function 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
#----
function testdir_clean() {
	local dir="$1"
	local var="$2"
	[ -z "$dir" ] && return 1
	if [ ! -d "$dir" ] ; then
		eval $var=""
		return 1
	else
		return 0
	fi
}

function 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"
		log "INFO" "$(gettext "Creating directory") $dirname"
	fi
	return 0
}

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

function user_create() {
	local username="$1"
	local groupname="$2"
	local description="$3"
	local home="$4"
	useradd -r -c "$description" -s "$(which bash)" -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"
	log "INFO" "$(gettext "Creating user") $username"
	return 0
}

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

function 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"
	log "INFO" "$(gettext "Creating group") $groupname"
	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
#----
function 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
#----
function 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
#----
function 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"
}


function 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"
}

function 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"
}

function locate_broker_etc()
{
	if [ -z "$BROKER_ETC" ]; then
		answer_with_testdir "$(gettext "Where is the configuration directory for 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"
}

function locate_broker_init_script()
{
	if [ -z "cbd" ]; then
		answer_with_testfile "$(gettext "Where is the init script for broker module daemon ?") [$DEFAULT_BROKER_INIT_SCRIPT]" "$DEFAULT_BROKER_INIT_SCRIPT" "BROKER_INIT_SCRIPT"
	fi
	BROKER_INIT_SCRIPT=`trim ${BROKER_INIT_SCRIPT}`
	export BROKER_INIT_SCRIPT
	log "INFO" "BROKER_INIT_SCRIPT: cbd"
}

#----
## Define where is Centreon log directory
## @Globals	CENTREON_LOG, DEFAULT_CENTREON_LOG
#----
function 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
#----
function 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
## @Globals	CENTREON_BINDIR, DEFAULT_CENTREON_BINDIR
#----
function locate_centreon_bindir() {
	if [ -n "$CENTREON_BINDIR" ] ; then
		dir_test_create "$CENTREON_BINDIR"
		if [ $? -ne 0 ] ; then
			CENTREON_BINDIR=""
		fi
	fi
	if [ -z "$CENTREON_BINDIR" ] ; then
		answer_with_createdir "$(gettext "Where is your Centreon binaries directory")" "$DEFAULT_CENTREON_BINDIR" "CENTREON_BINDIR"
		echo_success "$(gettext "Path" ) $CENTREON_BINDIR" "$ok"
	fi
	CENTREON_BINDIR=`trim ${CENTREON_BINDIR%/}`
	export CENTREON_BINDIR
	log "INFO" "CENTREON_BINDIR: $CENTREON_BINDIR"
}

#----
## Define where is Centreon data informations directory
## @Globals	CENTREON_DATADIR, DEFAULT_CENTREON_DATADIR
#----
function locate_centreon_datadir() {
	if [ -z "$CENTREON_DATADIR" ]; then
		answer_with_createdir "$(gettext "Where is your Centreon data informations directory")" "$DEFAULT_CENTREON_DATADIR" "CENTREON_DATADIR"
		echo_success "$(gettext "Path" ) $CENTREON_DATADIR" "$ok"
	elif [ ! -d "$CENTREON_DATADIR" -a "$silent_install" -eq 1 ]; then
		mkdir -p "$CENTREON_DATADIR"
		log "INFO" "$(gettext "Create") $CENTREON_DATADIR"
	fi
	CENTREON_DATADIR=`trim ${CENTREON_DATADIR%/}`
	export CENTREON_DATADIR
	log "INFO" "CENTREON_DATADIR: $CENTREON_DATADIR"
}

#----
## Define where is centreon install directory
## @Globals	INSTALL_DIR_CENTREON, DEFAULT_INSTALL_DIR_CENTREON
#----
function 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).
## filesUpload and filesGeneration directories
## @Globals	CENTREON_GENDIR, DEFAULT_CENTREON_GENDIR
#----
function locate_centreon_generationdir() {
	CENTREON_GENDIR="$INSTALL_DIR_CENTREON"
	export CENTREON_GENDIR
	log "INFO" "CENTREON_GENDIR: $CENTREON_GENDIR"
}

#----
## Define where is Centreon run directory (for .run file)
## @Globals	CENTREON_RUNDIR, DEFAULT_CENTREON_RUNDIR
#----
function 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
#----
function 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%/}`
	export CENTREON_VARLIB
	log "INFO" "CENTREON_VARLIB: $CENTREON_VARLIB"
}

#----
## Define where centStorage store a RRD file
## @Globals	CENTSTORAGE_RRD, DEFAULT_CENTSTORAGE_RRD
#----
function 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
#----
function 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
#----
function 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 centCore binary directory
## @Globals	CENTCORE_BINDIR, INSTALL_DIR_CENTREON, DEFAULT_CENTCORE_BINDIR
#----
function locate_centcore_bindir() {
	if [ -z "$CENTCORE_BINDIR" ] ; then
		answer_with_createdir "$(gettext "Where is your CentCore binary directory")" "$INSTALL_DIR_CENTREON/$DEFAULT_CENTCORE_BINDIR" "CENTCORE_BINDIR"
		echo_success "$(gettext "Path" ) $CENTCORE_BINDIR" "$ok"
	elif [ ! -d "$CENTCORE_BINDIR" -a "$silent_install" -eq 1 ] ; then
		mkdir -p $CENTCORE_BINDIR
		log "INFO" "$(gettext "Create") $CENTCORE_BINDIR"
	fi
	CENTCORE_BINDIR=`trim ${CENTCORE_BINDIR%/}`
	export CENTCORE_BINDIR
	log "INFO" "CENTCORE_BINDIR: $CENTCORE_BINDIR"
}

#----
## Define where is centPlugins temporary directory
## @Globals	CENTPLUGINS_TMP, DEFAULT_CENTPLUGINS_TMP
#----
function 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
#----
function 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
#----
function 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
#----
function 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
#----
function 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
#----
function 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
#----
function 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
#----
function locate_php_bin() {
	testfile_clean "$PHP_BIN" "PHP_BIN"
	if [ -z "$PHP_BIN" ] ; then
		php_binaries="php php5"
		for binary in $php_binaries ; do
			pathfind_ret "$binary" "PHP_BIN"
			if [ "$?" -eq 0 ] ; then
				PHP_BIN="$PHP_BIN/$binary"
				break
			fi
		done
		if [ -z "$PHP_BIN" ] ; then
			answer_with_testfile "$(gettext "Where is your php binary ? ")" "$DEFAULT_PHP_BIN" "PHP_BIN"
		fi
		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
#----
function 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
#----
function 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
#----
function 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"
}

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

#----
## Check if variable do not have most possibility
## @param	variable to check
## @return 0	True
## @return 1	False
#----
function 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
#----
function 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 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
}

#----
## Define apache service init script and ask to reload apache
## @return 0 	Apache reload OK
## @return 1	Apache reload FAIL
#----
function 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
	    local count_service=$(/bin/systemctl list-units | grep httpd | wc -l)
	    if [ "$count_service" -gt "0" ] ; then
	        service="httpd"
	    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 restart Apache server")" "$warning"
		log "WARN" "$(gettext "Unable to restart Apache server")"
	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
#----
function prepare_apache_config() {
	local directory="$1"

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



    # Check apache version
    apache_2_4=$(apachectl -v 2>/dev/null | grep '2\.[4-9]' | wc -l)

    # Prepare apache config
    if [ "$apache_2_4" -gt "0" ] ; then
    ${CAT} << __EOT__ > $directory/centreon.apache.conf
#
# Section add by Centreon Install Setup
#

Alias /centreon ${INSTALL_DIR_CENTREON}/www/

<LocationMatch ^/centreon/(.*\.php(/.*)?)$>
  ProxyPassMatch fcgi://127.0.0.1:9000${INSTALL_DIR_CENTREON}/www/\$1
</LocationMatch>

<Directory "${INSTALL_DIR_CENTREON}/www">
    Options Indexes
    AllowOverride AuthConfig Options
    Order allow,deny
    Allow from all
    Require all granted
</Directory>

RedirectMatch ^/$ /centreon/index.php
__EOT__
    else
	${CAT} << __EOT__ > $directory/centreon.apache.conf
#
# Section add by Centreon Install Setup
#

Alias /centreon ${INSTALL_DIR_CENTREON}/www/

<LocationMatch ^/centreon/(.*\.php(/.*)?)$>
  ProxyPassMatch fcgi://127.0.0.1:9000${INSTALL_DIR_CENTREON}/www/\$1
</LocationMatch>

<Directory "${INSTALL_DIR_CENTREON}/www">
    Options Indexes
    AllowOverride AuthConfig Options
    Order allow,deny
    Allow from all
    Require all granted
</Directory>

RedirectMatch ^/$ /centreon/index.php
__EOT__
    fi

	if [ -e $directory/centreon.apache.conf ] ; then
		return 0
	else
		log "INFO" "$(gettext "Problem when I generate an apache configuration")"
		return 1
	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, MONITORINGENGINE_INIT_SCRIPT
#----
function prepare_sudo_config() {
	local directory="$1"

    	locate_sudo
	# Find Monitoring Engine Init Script
	answer "$(gettext "What is the Monitoring engine init.d script ?") [$DEFAULT_MONITORINGENGINE_INIT_SCRIPT]" "$DEFAULT_MONITORINGENGINE_INIT_SCRIPT" "MONITORINGENGINE_INIT_SCRIPT"
	# 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 "cbd" ] && locate_broker_init_script
	[ -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 I generate a 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
#----
function 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
#----
function 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 me 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 me 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 with 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, MONITORINGENGINE_INIT_SCRIPT
## @Globals	BIN_RRDTOOL, WEB_USER, WEB_GROUP,
## @Globals	CENTREON_USER, BIN_MAIL
#----
function 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
/*
 * Centreon is developped with GPL Licence 2.0 :
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt
 * Developped by : Julien Mathis - Romain Le Merlus
 *
 * The Software is provided to you AS IS and WITH ALL FAULTS.
 * Centreon makes no representation and gives no warranty whatsoever,
 * whether express or implied, and without limitation, with regard to the quality,
 * any particular or intended purpose of the Software found on the Centreon web site.
 * In no event will Centreon be liable for any direct, indirect, punitive, special,
 * incidental or consequential damages however they may arise and even if Centreon has
 * been previously advised of the possibility of such damages.
 *
 * For 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_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['broker_init_script'] = "cbd";
\$conf_centreon['monitoring_user'] = "$MONITORINGENGINE_USER";
\$conf_centreon['monitoring_group'] = "$MONITORINGENGINE_GROUP";
\$conf_centreon['monitoring_etc'] = "$MONITORINGENGINE_ETC";
\$conf_centreon['monitoring_init_script'] = "centengine";
\$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 right 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, RRD_PERL, SUDO_FILE, WEB_USER, WEB_GROUP,
## @Globals	NAGIOS_GROUP, BIN_RRDTOOL, BIN_MAIL, PEAR_PATH, CENTREON_LOG,
## @Globals	CENTREON_ETC, CENTREON_GENDIR, CRON_D, NDOMOD_BINARY
#----
function createCentreonInstallConf() {
	${CAT} <<- __EOT__ > $CENTREON_ETC/instCentWeb.conf
	INSTALL_DIR_CENTREON=$INSTALL_DIR_CENTREON
	RRD_PERL=$RRD_PERL
	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_DATADIR=$CENTREON_DATADIR
	CENTREON_GENDIR=$CENTREON_GENDIR
	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
	BROKER_INIT_SCRIPT=cbd
	MONITORINGENGINE_ETC=$MONITORINGENGINE_ETC
	MONITORINGENGINE_INIT_SCRIPT=centengine
	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, RRD_PERL, CRON_D, INIT_D
#----
function 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_GENDIR=$CENTREON_GENDIR
	CENTREON_VARLIB=$CENTREON_VARLIB
	RRD_PERL=$RRD_PERL
	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 CentCore
## 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, RRD_PERL, CRON_D, INIT_D
#----
function createCentCoreInstallConf() {
	${CAT} <<- __EOT__ > $CENTREON_ETC/instCentCore.conf
	INSTALL_DIR_CENTREON=$INSTALL_DIR_CENTREON
	CENTREON_ETC=$CENTREON_ETC
	CENTREON_RUNDIR=$CENTREON_RUNDIR
	CENTREON_LOG=$CENTREON_LOG
	CENTREON_VARLIB=$CENTREON_VARLIB
	CENTREON_GENDIR=$CENTREON_GENDIR
	CENTCORE_BINDIR=$CENTCORE_BINDIR
	BIN_SSH=$BIN_SSH
	BIN_SCP=$BIN_SCP
	CENTREON_GROUP=$CENTREON_GROUP
	CENTREON_USER=$CENTREON_USER
	RRD_PERL=$RRD_PERL
	INIT_D=$INIT_D
	__EOT__

	echo_success "Create $CENTREON_ETC/instCentCore.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	RRD_PERL, CENTPLUGINS_TMP, NAGIOS_USER, NAGIOS_GROUP, INIT_D
## @Globals	SNMP_ETC, SNMPTT_BINDIR, CENTPLUGINSTRAPS_BINDIR, WEB_USER
#----
function 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
	RRD_PERL=$RRD_PERL
	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	RRD_PERL, CENTPLUGINS_TMP, NAGIOS_USER, NAGIOS_GROUP, INIT_D
## @Globals	SNMP_ETC, SNMPTT_BINDIR, CENTPLUGINSTRAPS_BINDIR, WEB_USER
#----
function 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
#----
function check_httpd_directory()
{
	if [ -z "$DIR_APACHE" -o -z "$DIR_APACHE_CONF" ] ; then
		if [ -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
#----
function 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
#----
function 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
#----
function 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
#----
function 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
#----
function 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
#----
function 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
}

#----
## Copy Source directory on temporary working directory
## Copy Source directory and prepare work and final
## @Globals	TMP_DIR
#----
function copyInTempFile()
{
	local srclistcp="composer.json bootstrap.php bin cron config logrotate doc GPL_LIB lib snmptrapd www plugins libinstall dbschema src"
	# 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 $TMP_DIR/src/"
		cp -Rf $BASE_DIR/$folder $TMP_DIR/src/
	done
}

#----
## 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
#----
function 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
		update-rc.d $service start 40 2 3 4 5 . stop 30 0 1 6 .
	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
## @return 0	OS found
## @return 1	OS not found
#----
function find_OS() {
	local distrib=$1
	local dist_found=""
	local system=""
	local lsb_release=""
	system="$(uname -s)"
	if [ "$system" = "Linux" ] ; then
		if [ "$(pathfind lsb_release; echo $?)" -eq "0" ] ; then
			lsb_release="$(lsb_release -i -s)"
		else
			lsb_release="NOT_FOUND"
		fi
		if [ "$lsb_release" = "Debian" ] || \
			[ "$lsb_release" = "Ubuntu" ] || \
			[ -e "/etc/debian_version" ] ; then
			dist_found="DEBIAN"
			log "INFO" "$(gettext "GNU/Linux Debian Distribution")"
		elif [ "$lsb_release" = "SUSE LINUX" ] || \
			[ -e "/etc/SuSE-release" ] ; then
			dist_found="SUSE"
			log "INFO" "$(gettext "GNU/Linux Suse Distribution")"
                elif [ "$lsb_release" = "openSUSE project" ] || \
			[ -e "/etc/SuSE-release" ] ; then
			dist_found="SUSE"
			log "INFO" "$(gettext "GNU/openSUSE Distribution")"
		elif [ "$lsb_release" = "RedHatEnterpriseES" ] || \
			[ "$lsb_release" = "Fedora" ] || \
			[ -e "/etc/redhat-release" ] ; then
			dist_found="REDHAT"
			log "INFO" "$(gettext "GNU/Linux Redhat Distribution")"
		else
			dist_found="NOT_FOUND"
			log "INFO" "$(gettext "GNU/Linux distribution not found")"
			return 1
		fi
	elif [ "$system" = "FreeBSD" ] ; then
		dist_found="FREEBSD"
		log "INFO" "$(gettext "FreeBSD System")"
	elif [ "$system" = "AIX" ] ; then
		dist_found="AIX"
		log "INFO" "$(gettext "AIX System")"
	elif [ "$system" = "SunOS" ] ; then
		dist_found="SUNOS"
		log "INFO" "$(gettext "SunOS System")"
	else
		dist_found="NOT_FOUND"
		log "INFO" "$(gettext "System not found")"
	fi

	eval $distrib=$dist_found
	return 0
}

#----
## use this function to clean and exit centreon install
## This function use <@function purge_centreon_tmp_dir> function.
## TODO: Need to add fonctionnality
##      - delete install file
##      - restore inital rigth
##      - ...
#----
function 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 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
#----
function 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
#----
function 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 me 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
#----
function 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 me 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 	directoty where to find
## @param	sub directory to find
## @param	file to search (possible to use pattern)
## @param	variable where define a list of file (temporaty file)
## @Globals	LOG_FILE, TMP_DIR
#----
function 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
#----
function 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
#----
function add_group() {
	local user=$1
	local group=$2
	if [ -z "$user" -o -z "$group" ]; then
		echo_failure "$(gettext "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
#----
function 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
}

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

#----
## Check the minimum version PHP
## @return 0	Version ok
## @return 1	Version too old
## @Globals	PHP_BIN
#----
function check_php_version() {
	local version=$1

	echo -e "$(gettext "Check PHP version")"

	${PHP_BIN} -r "version_compare(phpversion(), getenv('PHP_VERSION'), 'ge') ? exit(0) : exit (1);"
	if [ $? -ne 0 ]; then
		echo_failure "$(gettext "The PHP version is too old.") : minimum ${version} | your $(php -r 'echo phpversion();')" "$fail"
		return 1
	fi
	return 0
}

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


#----
## Check is the php modules are installed
## @return 0	All modules are installed
## @return 1	Missing modules
## @Globals	PHP_BIN PHP_MODULES_LIST
#----
function check_php_modules() {
	local return_value=0
	echo -e "$(gettext "Check PHP modules")"
	while read module; do
		if [ -n "${module}" ]; then
			echo -en "\t${module}\t\t"
			${PHP_BIN} -m | grep -e "^${module}$" &>/dev/null
			if [ $? -eq 0 ]; then
				echo -e "\033[u\033[60G\033[1;32mOK\033[0m"
			else
				echo -e "\033[u\033[60G\033[1;31mNOK\033[0m"
				return_value=1
			fi
		fi
	done < "${INSTALL_VARS_DIR}/${PHP_MODULES_LIST}"
	return ${return_value}
}

#----
## Locate the fpm-php service
## @return 0 The FPM PHP service found
## @Globals PHP_FPM_SERVICE
#----
function locate_fpm_php_service()  {
	local valid=1
	${SERVICE_BINARY} "fpm-php" status &>/dev/null
	if [ $? -eq 4 ]; then
		while [ ${valid} -eq 1 ]; do
			answer "$(gettext "What is the fpm-php service name ?")" "fpm-php" \
				"PHP_FPM_SERVICE"
			${SERVICE_BINARY} "${PHP_FPM_SERVICE}" status &>/dev/null
			if [ $? -ne 4 ]; then
				valid=0
			fi
		done
	else
		PHP_FPM_SERVICE="fpm-php"
	fi
	echo -e "$(gettext "The fpm-php service") : ${PHP_FPM_SERVICE}"
	return 0
}
