#!/bin/bash
################################################################################
# system-config-distributed-monitoring                                         #
#                                                                              #
# Copyright (C) 2013 Olivier LI-KIANG-CHEONG                                   #
#                                                                              #
# 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.                                 #
#                                                                              #
# You should have received a copy of the GNU General Public License along      #
# with this program; if not, write to the Free Software Foundation, Inc.,      #
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.                  #
#                                                                              #
################################################################################
# Description : Configure distributed monitoring with Centreon and Nagios      #
# Including configuration database and adding poller                           #
################################################################################
# Version : 1.5                                                                #
# ChangeLog :                                                                  #
#  Fix feature #3512393 : adding poller in fan standalone                      #
#  Fix configuration since FAN 2.2 -> 2.3                                      #
#  Add option configdatabase-createuse                                         #
#  Add option poller-configtrap                                                #
#  Update for centreon 2.4.0                                                   #
#  Update for centreon 2.4.1                                                   #
#                                                                              #
################################################################################
# Author : Olivier LI-KIANG-CHEONG <lkco@gezen.fr>                             #
#          Thibault COHEN <titilambert@gmail.com>                              #
################################################################################

PROGNAME=$0
ACTION_NAME=$1 # addpoller | configdatabase | configdatabase-createuser | poller-configtrap
NAGIOS_USER=nagios
NAGIOS_HOME=/var/log/nagios
CENTREON_CONFIG=/etc/centreon/conf.pm
NAGVIS_INI=/etc/nagvis/nagvis.ini.php
NAGIOS_DB_NAME=nagios
CENTREON_DB_NAME=$(cat $CENTREON_CONFIG | grep mysql_database_oreon | awk -F\" '{print $2}')
CENTREON_DB_USER=$(cat $CENTREON_CONFIG | grep mysql_user | awk -F\" '{print $2}')
CENTREON_DB_PASSWORD=$(cat $CENTREON_CONFIG | grep mysql_passwd | awk -F\" '{print $2}')
MYSQL_DB_ADDRESS=$(cat $CENTREON_CONFIG | grep mysql_host | awk -F\" '{print $2}')
QUIET_MODE=0
DEBUG=0 # O or 1

function verbose_log() {
    [ "$DEBUG" == "1" ] && echo "[$(date '+%d/%m/%Y %H:%M:%S')] $1"
}


if [ "$ACTION_NAME" == "-h" ] || [ "$ACTION_NAME" == "--help" ] ; then
    echo "To configure distributed monitoring, you have to install a minimum a fan-central server, a fan-database server"
    echo "and a fan-poller server. For a first launching of $ PROGNAME you must configure the database"
    echo "  - Configure Database : "
    echo "      $PROGNAME [-y|--yes] configdatabase [DATABASE_IP] [DATABASE_ROOT_PASSWD] [CENTRAL_IP]"
    echo "  - Add a new poller : "
    echo "      $PROGNAME [-y|--yes] addpoller [POLLER_NAME] [POLLER_IP] [POLLER_ROOT_PASSWD] [MYSQL_DB_ADDRESS] [CENTRAL_IP]"
    echo "  - Interactive mode : "
    echo "      $PROGNAME" 
    echo ""
    echo "Options"
    echo "   -y, --yes"
    echo "      Assume yes; assume that the answer to any question which would be asked is yes."
    echo "   -h, --help"
    echo "      Display this help and exit"
    exit 0
fi

if [ "$ACTION_NAME" == "-y" ] || [ "$ACTION_NAME" == "--yes" ] ; then
    shift 1
    ACTION_NAME=$1
    QUIET_MODE=1
fi

while [ "$ACTION_NAME" != "addpoller" ] && [ "$ACTION_NAME" != "configdatabase" ] && [ "$ACTION_NAME" != "configdatabase-createuser" ] && [ "$ACTION_NAME" != "poller-configtrap" ] ; do
    echo -n "Choose an action to do (addpoller or configdatabase):"
    read ACTION_NAME
    if [ "$ACTION_NAME" != "addpoller" ] && [ "$ACTION_NAME" != "configdatabase" ] && [ "$ACTION_NAME" != "configdatabase-createuser" ] && [ "$ACTION_NAME" != "poller-configtrap" ]; then
        echo "Wrong choise. You must choose : addpoller or configdatabase"
    fi
done

if [ "$ACTION_NAME" == "poller-configtrap" ] ; then
    echo "[INFO] poller-configtrap option should only be launched after an upgrade FAN 2.2 -> 2.3"
    echo "In order for a poller can receive snmp trap, it needs access to the centreon2 database with SELECT privilege"

    verbose_log "Retrieve poller information"
    #query1="SELECT id,name,ns_ip_address FROM nagios_server WHERE ns_activate='1' AND localhost='0';"
    query1="SELECT name FROM nagios_server WHERE ns_activate='1' AND localhost='0';"
    verbose_log "query: $query1"
    result1=$(echo $query1 | /usr/bin/mysql -h $MYSQL_DB_ADDRESS --skip-column-name -u $CENTREON_DB_USER -p$CENTREON_DB_PASSWORD -D $CENTREON_DB_NAME)
    verbose_log "result1 : $result1"
    all_poller=`echo $result1 | awk {'print $0'}` 
    echo "Your choices are: $all_poller"
    echo -n "Which poller do you want to choose ? : "
    read POLLER_NAME

    query2="SELECT ns_ip_address FROM nagios_server WHERE name='$POLLER_NAME';"
    result2=$(echo $query2 | /usr/bin/mysql -h $MYSQL_DB_ADDRESS --skip-column-name -u $CENTREON_DB_USER -p$CENTREON_DB_PASSWORD -D $CENTREON_DB_NAME)
    verbose_log "result2 : $result2"
    POLLER_IP=`echo $result2 | awk {'print $1'}`
    verbose_log "Retreive $POLLER_NAME ip : $POLLER_IP"

    if [ -z "$POLLER_ROOT_PASSWD" ] ; then
        echo -n "Give me the root password of \"$POLLER_NAME\" :"
        stty -echo
        read POLLER_ROOT_PASSWD
        stty echo
        echo ""
    fi


    if [ "$QUIET_MODE" == "0" ] ; then 
        echo "[INFO] You must enable root user to login by ssh to \"$POLLER_NAME\" by ssh."
        echo "If this is not the case, edit /etc/ssh/sshd_config on \"$POLLER_NAME\" and add \"PermitRootLogin yes\""
        res="not_define"
        while [ "$res" != "y" ] && [ "$res" != "n" ] && [ ! -z "$res" ] ; do
            default="n"
            echo -n "Do you want continu ? [y/n], default to [$default]:"
            read res
            [ -z "$res" ] && res="$default"
        done
        if [ "$res" == "n" ] ; then
            echo "Abort..."
            exit 101
        fi
    fi

    USER_SSH="monitor"
    USER_DB_PRIVILEGE="monitor"
    USER_DB_PASSWD=$(< /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c8)
    echo "[INFO] Adduser mysql user for poller : \"$USER_DB_PRIVILEGE\" with password \"$USER_DB_PASSWD\""
    verbose_log "Adduser mysql user for poller : \"$USER_DB_PRIVILEGE\" with password \"$USER_DB_PASSWD\""

    # flush privileges
    tmplocalfile="$(mktemp /tmp/fileXXXXXX).sql"
    tmpremotefile="$(mktemp /tmp/fileXXXXXX).sql"
    verbose_log "tmplocalfile : $tmplocalfile"
    verbose_log "tmpremotefile : $tmpremotefile"

    echo "[INFO] Add GRANT SELECT for centreon2"
    query="GRANT SELECT ON centreon2.* TO '$USER_DB_PRIVILEGE'@'$POLLER_IP' IDENTIFIED BY '$USER_DB_PASSWD'; 
FLUSH PRIVILEGES;"
    verbose_log "mysql query : $query"
    echo $query > $tmplocalfile
    verbose_log "Run: scp -o StrictHostKeyChecking=no $tmplocalfile $USER_SSH@$MYSQL_DB_ADDRESS:$tmpremotefile"
    scp -o StrictHostKeyChecking=no $tmplocalfile $USER_SSH@$MYSQL_DB_ADDRESS:$tmpremotefile
    verbose_log "Run: ssh -o StrictHostKeyChecking=no $USER_SSH@$MYSQL_DB_ADDRESS \"mysql -u root < $tmpremotefile ; rm -f $tmpremotefile\""
    ssh -o StrictHostKeyChecking=no $USER_SSH@$MYSQL_DB_ADDRESS "mysql -u root < $tmpremotefile ; rm -f $tmpremotefile"
    rm -f $tmplocalfile

    # Modify /etc/centreon2/conf.pm on poller
    verbose_log "Modify /etc/centreon/conf.pm on poller"
    tmpfileconf="$(mktemp /tmp/fileXXXXXX).conf"
    echo "\$mysql_host = \"$MYSQL_DB_ADDRESS\";" >> $tmpfileconf
    echo "\$mysql_user = \"$USER_DB_PRIVILEGE\";" >> $tmpfileconf
    echo "\$mysql_passwd = \"$USER_DB_PASSWD\";" >> $tmpfileconf
    echo "\$mysql_database_oreon = \"centreon2\";" >> $tmpfileconf
    echo "\$mysql_database_ods = \"centreon2_storage\";" >> $tmpfileconf
    echo "1;" >> $tmpfileconf

    verbose_log "Run expect: transfert $tmpfileconf by scp"
    VAR=$(expect -c "
        spawn scp -o StrictHostKeyChecking=no $tmpfileconf root@$POLLER_IP:/etc/centreon/conf.pm
        expect \"*password:*\"
        send -- \"$POLLER_ROOT_PASSWD\r\"
        expect eof
        ")

    rm -f $tmpfileconf

    echo "[INFO] : If you want to reconfigure an other poller, re-run : $PROGNAME poller-configtrap"
fi

if [ "$ACTION_NAME" == "configdatabase-createuser" ] ; then
    echo "[INFO] configdatabase-createuser option should only be launched after an upgrade FAN 2.2 -> 2.3"
    echo "This option create only an user monitor in database server to add GRANT SELECT PRIVILEGE"
    DATABASE_IP=$2
    DATABASE_ROOT_PASSWD=$3

    if [ -z "$DATABASE_IP" ] ; then
        echo -n "Give me the IP address of database server :"
        read DATABASE_IP
    fi

    if [ -z "$DATABASE_ROOT_PASSWD" ] ; then
        echo -n "Give me the root password of database server :"
        stty -echo
        read DATABASE_ROOT_PASSWD
        stty echo
        echo ""
    fi
   
    if [ "$QUIET_MODE" == "0" ] ; then 
        echo "[INFO] You must enable root user to login by ssh to database server \"$DATABASE_IP\" by ssh."
        echo "If this is not the case, edit /etc/ssh/sshd_config on database server and add \"PermitRootLogin yes\""
        res="not_define"
        while [ "$res" != "y" ] && [ "$res" != "n" ] && [ ! -z "$res" ] ; do
            default="n"
            echo -n "Do you want continu ? [y/n], default to [$default]:"
            read res
            [ -z "$res" ] && res="$default"
        done
        if [ "$res" == "n" ] ; then
            echo "Abort..."
            exit 101
        fi
    fi

    echo "Check if root user has a ssh key"
    
    if [ ! -f ~/.ssh/id_rsa ] ; then
        echo "Create a ssh key without password"
        VAR=$(expect -c "
        spawn ssh-keygen -t rsa
        expect \"*Enter file in which to save the key *\"
        send -- \"\r\"
        expect \"*Enter passphrase*\"
        send -- \"\r\"
        expect \"*Enter same passphrase again:*\"
        send -- \"\r\"
        expect eof
        ")
        
        verbose_log $VAR 
        if [ ! -f ~/.ssh/id_rsa ] ; then
            echo "[ERROR] ssh key ~/.ssh/id_rsa don't created"
            exit 102
        fi
    else 
        echo "Root user has a ssh key"
    fi
    
    echo "Create monitor user on \"DATABASE SERVER\""
    VAR=$(expect -c "
        spawn ssh -o StrictHostKeyChecking=no root@$DATABASE_IP \"adduser monitor\"
        expect \"*password:*\"
        send -- \"$DATABASE_ROOT_PASSWD\r\"
        expect eof
        ")
    verbose_log $VAR 

    USER_SSH_PASSWD=$(< /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c8)
    echo "Set random password for monitor user"
    verbose_log "Random password : $USER_SSH_PASSWD"
    VAR=$(expect -c "
        spawn ssh -o StrictHostKeyChecking=no root@$DATABASE_IP \"passwd monitor\"
        expect \"*password:*\"
        send -- \"$DATABASE_ROOT_PASSWD\r\"
        expect \"*New UNIX password:*\"
        send -- \"$USER_SSH_PASSWD\r\"
        expect \"*Retype new UNIX password:*\"
        send -- \"$USER_SSH_PASSWD\r\"
        expect eof
        ")
    verbose_log $VAR 
    
    echo "Copy ssh key to monitor@DATABASE"
    VAR=$(expect -c "
        spawn ssh-copy-id -i /root/.ssh/id_rsa.pub monitor@$DATABASE_IP
        expect { 
            \"*Are you sure you want to continue connecting*\"
            {
                sleep 1
                send "yes\r"
                exp_continue
            }
            \"*password:*\"
            {
                sleep 1
                send \"$USER_SSH_PASSWD\r\"
                exp_continue
            }
        }
    ")
    verbose_log $VAR 


fi

if [ "$ACTION_NAME" == "configdatabase" ] ; then
    DATABASE_IP=$2
    DATABASE_ROOT_PASSWD=$3

    if [ -z "$DATABASE_IP" ] ; then
        echo -n "Give me the IP address of database server :"
        read DATABASE_IP
    fi

    if [ -z "$DATABASE_ROOT_PASSWD" ] ; then
        echo -n "Give me the root password of database server :"
        stty -echo
        read DATABASE_ROOT_PASSWD
        stty echo
        echo ""
    fi
   
    CENTRAL_IP=$4
    if [ "$DATABASE_IP" == "127.0.0.1" ]; then
        CENTRAL_IP=$DATABASE_IP
    fi

    if [ -z "$CENTRAL_IP" ] ; then
        CENTRAL_IP=$(ifconfig eth0 | awk '/inet adr/ {split ($2,A,":"); print A[2]}')
        
        [ ! -z "$CENTRAL_IP" ] && ip_default=$CENTRAL_IP
        echo -n "What's the IP address of fan-central"
        [ ! -z "$CENTRAL_IP" ] && echo -n " (default $ip_default)"
        echo -n " :"
        read ip_default
        [ ! -z "$ip_default" ] && CENTRAL_IP=$ip_default
    fi

    if [ "$QUIET_MODE" == "0" ] ; then 
        echo "[INFO] You must enable root user to login by ssh to database server \"$DATABASE_IP\" by ssh."
        echo "If this is not the case, edit /etc/ssh/sshd_config on database server and add \"PermitRootLogin yes\""
        res="not_define"
        while [ "$res" != "y" ] && [ "$res" != "n" ] && [ ! -z "$res" ] ; do
            default="n"
            echo -n "Do you want continu ? [y/n], default to [$default]:"
            read res
            [ -z "$res" ] && res="$default"
        done
        if [ "$res" == "n" ] ; then
            echo "Abort..."
            exit 101
        fi
    fi

#######################
    echo "Check if root user has a ssh key"
    
    if [ ! -f ~/.ssh/id_rsa ] ; then
        echo "Create a ssh key without password"
        VAR=$(expect -c "
        spawn ssh-keygen -t rsa
        expect \"*Enter file in which to save the key *\"
        send -- \"\r\"
        expect \"*Enter passphrase*\"
        send -- \"\r\"
        expect \"*Enter same passphrase again:*\"
        send -- \"\r\"
        expect eof
        ")
        
        verbose_log $VAR 
        if [ ! -f ~/.ssh/id_rsa ] ; then
            echo "[ERROR] ssh key ~/.ssh/id_rsa don't created"
            exit 102
        fi
    else 
        echo "Root user has a ssh key"
    fi
    
    USER_SSH="monitor"
    echo "Create $USER_SSH user on \"DATABASE_SERVER\""
    VAR=$(expect -c "
        spawn ssh -o StrictHostKeyChecking=no root@$DATABASE_IP \"adduser $USER_SSH\"
        expect \"*password:*\"
        send -- \"$DATABASE_ROOT_PASSWD\r\"
        expect eof
        ")
    verbose_log $VAR 

    USER_SSH_PASSWD=$(< /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c8)
    echo "Set random password for monitor user"
    verbose_log "Random password : $USER_SSH_PASSWD"
    VAR=$(expect -c "
        spawn ssh -o StrictHostKeyChecking=no root@$DATABASE_IP \"passwd $USER_SSH\"
        expect \"*password:*\"
        send -- \"$DATABASE_ROOT_PASSWD\r\"
        expect \"*New UNIX password:*\"
        send -- \"$USER_SSH_PASSWD\r\"
        expect \"*Retype new UNIX password:*\"
        send -- \"$USER_SSH_PASSWD\r\"
        expect eof
        ")
    verbose_log $VAR 
    
    echo "Copy ssh key to $USER_SSH@DATABASE_SERVER"
    VAR=$(expect -c "
        spawn ssh-copy-id -i /root/.ssh/id_rsa.pub $USER_SSH@$DATABASE_IP
        expect { 
            \"*password:*\"
            {
                sleep 1
                send \"$USER_SSH_PASSWD\r\"
                exp_continue
            }
        }
    ")
    verbose_log $VAR 
#######################


    USER_DB_PRIVILEGE="monitor"
    USER_DB_PASSWD=$(< /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c8)
    echo "[INFO] Adduser mysql user : \"$USER_DB_PRIVILEGE\" with password \"$USER_DB_PASSWD\""
    verbose_log "Adduser mysql user : \"$USER_DB_PRIVILEGE\" with password \"$USER_DB_PASSWD\""

    # flush privileges
    tmplocalfile="$(mktemp /tmp/fileXXXXXX).sql"
    tmpremotefile="$(mktemp /tmp/fileXXXXXX).sql"
    verbose_log "tmplocalfile : $tmplocalfile"
    verbose_log "tmpremotefile : $tmpremotefile"

    echo "[INFO] Add GRANT PRIVILEGES for nagios centreon2 centreon2_storage database"
    query="GRANT ALL PRIVILEGES ON nagios.* TO '$USER_DB_PRIVILEGE'@'$CENTRAL_IP' IDENTIFIED BY '$USER_DB_PASSWD'; 
GRANT ALL PRIVILEGES ON centreon2.* TO '$USER_DB_PRIVILEGE'@'$CENTRAL_IP' IDENTIFIED BY '$USER_DB_PASSWD'; 
GRANT ALL PRIVILEGES ON centreon2_storage.* TO '$USER_DB_PRIVILEGE'@'$CENTRAL_IP' IDENTIFIED BY '$USER_DB_PASSWD'; 
FLUSH PRIVILEGES;"
    verbose_log "mysql query : $query"
    echo $query > $tmplocalfile
    verbose_log "Run expect: transfert $tmplocalfile by scp"
    VAR=$(expect -c "
        spawn scp -o StrictHostKeyChecking=no $tmplocalfile root@$DATABASE_IP:$tmpremotefile
        expect \"*password:*\"
        send -- \"$DATABASE_ROOT_PASSWD\r\"
        expect eof
        ")

    rm -f $tmplocalfile

    VAR=$(expect -c "
        spawn ssh -o StrictHostKeyChecking=no root@$DATABASE_IP \"mysql < $tmpremotefile ; rm -f $tmpremotefile\"
        expect \"*password:*\"
        send -- \"$DATABASE_ROOT_PASSWD\r\"
        expect eof
        ")
    
    verbose_log "$VAR"

    echo "[INFO] Modify /etc/nagios/ndo2db.cfg /etc/nagvis/nagvis.ini.php /etc/centreon/centreon.conf.php /etc/centreon/conf.pm"
    # /etc/nagios/ndo2db.cfg
    verbose_log "Modify /etc/nagios/ndo2db.cfg"
    sed -i "s:^db_host=.*:db_host=$DATABASE_IP:" /etc/nagios/ndo2db.cfg
    sed -i "s:^db_user=.*:db_user=$USER_DB_PRIVILEGE:" /etc/nagios/ndo2db.cfg
    sed -i "s:^db_pass=.*:db_pass=$USER_DB_PASSWD:" /etc/nagios/ndo2db.cfg
    
    # /etc/nagvis/nagvis.ini.php
    verbose_log "Modify /etc/nagvis/nagvis.ini.php"
    sed -i "s:dbhost=.*:dbhost=\"$DATABASE_IP\":" /etc/nagvis/nagvis.ini.php
    sed -i "s:dbuser=.*:dbuser=\"$USER_DB_PRIVILEGE\":" /etc/nagvis/nagvis.ini.php
    sed -i "s:dbpass.*:dbpass=\"$USER_DB_PASSWD\":" /etc/nagvis/nagvis.ini.php

    # /etc/centreon2/centreon.conf.php
    verbose_log "Modify /etc/centreon/centreon.conf.php"
    sed -i "s:\$conf_centreon.*hostCentreon.*:\$conf_centreon['hostCentreon'] = \"$DATABASE_IP\";:" /etc/centreon/centreon.conf.php
    sed -i "s:\$conf_centreon.*hostCentstorage.*:\$conf_centreon['hostCentstorage'] = \"$DATABASE_IP\";:" /etc/centreon/centreon.conf.php
    sed -i "s:\$conf_centreon.*user.*:\$conf_centreon['user'] = \"$USER_DB_PRIVILEGE\";:" /etc/centreon/centreon.conf.php
    sed -i "s:\$conf_centreon.*password.*:\$conf_centreon['password'] = \"$USER_DB_PASSWD\";:" /etc/centreon/centreon.conf.php

    # /etc/centreon2/conf.pm
    verbose_log "Modify /etc/centreon/conf.pm"
    sed -i "s:\$mysql_host.*:\$mysql_host = \"$DATABASE_IP\";:" /etc/centreon/conf.pm
    sed -i "s:\$mysql_user.*:\$mysql_user = \"$USER_DB_PRIVILEGE\";:" /etc/centreon/conf.pm
    sed -i "s:\$mysql_passwd.*:\$mysql_passwd = \"$USER_DB_PASSWD\";:" /etc/centreon/conf.pm

    # db "centreon2" table "ndo2db"
    echo "[INFO] Update cfg_ndo2db"
    verbose_log "Update cfg_ndo2db"
    query2="UPDATE cfg_ndo2db SET db_host='$DATABASE_IP' , db_user='$USER_DB_PRIVILEGE' , db_pass='$USER_DB_PASSWD' WHERE local='0' AND activate='1'"
    verbose_log "query : $query2"
    $(echo $query2 | mysql -h $DATABASE_IP -u $USER_DB_PRIVILEGE -p$USER_DB_PASSWD -D centreon2)

    # Restart service ndo2db centcore centstorage
    verbose_log "Restart ndo2db"
    /etc/init.d/ndo2db restart

    verbose_log "Restart centcore"
    /etc/init.d/centcore stop
    # Check centcore status
    centcore_pid=$(ps -ef | grep centcore | grep -v grep | awk -F " " '{print $2}')
    if let $centcore_pid 2>/dev/null
    then
        verbose_log "Force to kill centcore $centcore_pid"
        kill -9 $centcore_pid 2> /dev/null
    fi 
    /etc/init.d/centcore start
    
    verbose_log "Restart centstorage"
    /etc/init.d/centstorage stop
    # Check centcore status
    centstorage_pid=$(ps -ef | grep centstorage | grep -v grep | awk -F " " '{print $2}')
    if let $centstorage_pid 2>/dev/null
    then
        verbose_log "Force to kill centstorage $centstorage_pid"
        kill -9 $centstorage_pid 2> /dev/null
    fi 
    /etc/init.d/centstorage start

fi

if [ "$ACTION_NAME" == "addpoller" ] ; then
    POLLER_NAME=$2
    POLLER_IP=$3
    POLLER_ROOT_PASSWD=$4
    NDO_INSTANCE_NAME=$POLLER_NAME
    if [ -z "$POLLER_NAME" ] ; then
        echo -n "Give me the new Poller Name ? (no space) :"
        read POLLER_NAME
        POLLER_NAME=$(echo $POLLER_NAME | sed 's/ //g')
    fi
    
    if [ -z "$POLLER_IP" ] ; then
        echo -n "Give me the IP address of \"$POLLER_NAME\" :"
        read POLLER_IP
    fi
    
    if [ -z "$POLLER_ROOT_PASSWD" ] ; then
        echo -n "Give me the root password of \"$POLLER_NAME\" :"
        stty -echo
        read POLLER_ROOT_PASSWD
        stty echo
        echo ""
    fi
    
    if [ -z "$MYSQL_DB_ADDRESS" ] ; then
        echo -n "Give me the IP address of the database server :"
        read MYSQL_DB_ADDRESS
    fi

    CENTRAL_IP=$5
    if [ -z "$CENTRAL_IP" ] ; then
        CENTRAL_IP=$(ifconfig eth0 | awk '/inet adr/ {split ($2,A,":"); print A[2]}')
        
        [ ! -z "$CENTRAL_IP" ] && ip_default=$CENTRAL_IP
        echo -n "What's the IP address of fan-central"
        [ ! -z "$CENTRAL_IP" ] && echo -n " (default $ip_default)"
        echo -n " :"
        read ip_default
        [ ! -z "$ip_default" ] && CENTRAL_IP=$ip_default
    fi

    if [ "$QUIET_MODE" == "0" ] ; then 
        echo "[INFO] You must enable root user to login by ssh to \"$POLLER_NAME\" by ssh."
        echo "If this is not the case, edit /etc/ssh/sshd_config on \"$POLLER_NAME\" and add \"PermitRootLogin yes\""
        res="not_define"
        while [ "$res" != "y" ] && [ "$res" != "n" ] && [ ! -z "$res" ] ; do
            default="n"
            echo -n "Do you want continu ? [y/n], default to [$default]:"
            read res
            [ -z "$res" ] && res="$default"
        done
        if [ "$res" == "n" ] ; then
            echo "Abort..."
            exit 101
        fi
    fi

###############################

    USER_SSH="monitor"
    USER_DB_PRIVILEGE="monitor"
    USER_DB_PASSWD=$(< /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c8)
    echo "[INFO] Adduser mysql user for poller : \"$USER_DB_PRIVILEGE\" with password \"$USER_DB_PASSWD\""
    verbose_log "Adduser mysql user for poller : \"$USER_DB_PRIVILEGE\" with password \"$USER_DB_PASSWD\""

    # flush privileges
    tmplocalfile="$(mktemp /tmp/fileXXXXXX).sql"
    tmpremotefile="$(mktemp /tmp/fileXXXXXX).sql"
    verbose_log "tmplocalfile : $tmplocalfile"
    verbose_log "tmpremotefile : $tmpremotefile"

    echo "[INFO] Add GRANT SELECT for centreon2"
    query="GRANT SELECT ON centreon2.* TO '$USER_DB_PRIVILEGE'@'$POLLER_IP' IDENTIFIED BY '$USER_DB_PASSWD'; 
FLUSH PRIVILEGES;"
    verbose_log "mysql query : $query"
    echo $query > $tmplocalfile
    verbose_log "Run: scp -o StrictHostKeyChecking=no $tmplocalfile $USER_SSH@$MYSQL_DB_ADDRESS:$tmpremotefile"
    scp -o StrictHostKeyChecking=no $tmplocalfile $USER_SSH@$MYSQL_DB_ADDRESS:$tmpremotefile
    verbose_log "Run: ssh -o StrictHostKeyChecking=no $USER_SSH@$MYSQL_DB_ADDRESS \"mysql -u root < $tmpremotefile ; rm -f $tmpremotefile\""
    ssh -o StrictHostKeyChecking=no $USER_SSH@$MYSQL_DB_ADDRESS "mysql -u root < $tmpremotefile ; rm -f $tmpremotefile"
    rm -f $tmplocalfile

    # Modify /etc/centreon2/conf.pm on poller
    verbose_log "Modify /etc/centreon/conf.pm on poller"
    tmpfileconf="$(mktemp /tmp/fileXXXXXX).conf"
    echo "\$mysql_host = \"$MYSQL_DB_ADDRESS\";" >> $tmpfileconf
    echo "\$mysql_user = \"$USER_DB_PRIVILEGE\";" >> $tmpfileconf
    echo "\$mysql_passwd = \"$USER_DB_PASSWD\";" >> $tmpfileconf
    echo "\$mysql_database_oreon = \"centreon2\";" >> $tmpfileconf
    echo "\$mysql_database_ods = \"centreon2_storage\";" >> $tmpfileconf
    echo "" >> $tmpfileconf
    echo "\$instance_mode = \"poller\";" >> $tmpfileconf
    echo "\$cmdFile = \"/var/log/nagios/rw/nagios.cmd\";" >> $tmpfileconf
    echo "" >> $tmpfileconf
    echo "1;" >> $tmpfileconf

    verbose_log "Run expect: transfert $tmpfileconf by scp"
    VAR=$(expect -c "
        spawn scp -o StrictHostKeyChecking=no $tmpfileconf root@$POLLER_IP:/etc/centreon/conf.pm
        expect \"*password:*\"
        send -- \"$POLLER_ROOT_PASSWD\r\"
        expect eof
        ")

    rm -f $tmpfileconf


###############################

    echo "Check if nagios user has a ssh key"
    chown $NAGIOS_USER:$NAGIOS_USER $NAGIOS_HOME
    
    if [ ! -f $NAGIOS_HOME/.ssh/id_rsa ] ; then
        echo "Create a ssh key without password"
        VAR=$(expect -c "
        spawn su - nagios -c \"ssh-keygen -t rsa\"
        expect \"*Enter file in which to save the key *\"
        send -- \"\r\"
        expect \"*Enter passphrase*\"
        send -- \"\r\"
        expect \"*Enter same passphrase again:*\"
        send -- \"\r\"
        expect eof
        ")
        
        verbose_log $VAR 
        if [ ! -f $NAGIOS_HOME/.ssh/id_rsa ] ; then
            echo "[ERROR] ssh key $NAGIOS_HOME/.ssh/id_rsa don't created"
            exit 102
        fi
    else 
        echo "Nagios user has a ssh key"
    fi
    
    echo "Create a random password for nagios user on \"$POLLER_NAME\""
    NAGIOS_PASSWD=$(< /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c8)
    verbose_log "Random password : $NAGIOS_PASSWD"
    VAR=$(expect -c "
        spawn ssh -o StrictHostKeyChecking=no root@$POLLER_IP \"passwd nagios\"
        expect \"*password:*\"
        send -- \"$POLLER_ROOT_PASSWD\r\"
        expect \"*New UNIX password:*\"
        send -- \"$NAGIOS_PASSWD\r\"
        expect \"*Retype new UNIX password:*\"
        send -- \"$NAGIOS_PASSWD\r\"
        expect eof
        ")
    verbose_log $VAR 
     
    echo "Copy ssh key to poller \"$POLLER_NAME\""
    VAR=$(expect -c "
        spawn ssh-copy-id -i $NAGIOS_HOME/.ssh/id_rsa.pub nagios@$POLLER_IP
        expect { 
            \"*Are you sure you want to continue connecting*\"
            {
                sleep 1
                send "yes\r"
                exp_continue
            }
            \"*password:*\"
            {
                sleep 1
                send \"$NAGIOS_PASSWD\r\"
                exp_continue
            }
        }
    ")
    verbose_log $VAR 
    # Todo check return code
    
    verbose_log "copy ~/.ssh/known_hosts $NAGIOS_HOME/.ssh/known_hosts"
    cp ~/.ssh/known_hosts $NAGIOS_HOME/.ssh/known_hosts
    chmod 644 $NAGIOS_HOME/.ssh/known_hosts
    chown $NAGIOS_USER:$NAGIOS_USER $NAGIOS_HOME/.ssh/known_hosts
    
    echo "Add configuration poller in to centreon database"
    verbose_log "Mysql connect to : -h $MYSQL_DB_ADDRESS -u $CENTREON_DB_USER -p $CENTREON_DB_PASSWORD -D $CENTREON_DB_NAME"
    verbose_log "Create new poller in centreon"
    query="INSERT INTO nagios_server (name, localhost, ns_ip_address, ssh_port, nagios_bin, nagiostats_bin, nagios_perfdata, init_script, ns_activate, monitoring_engine, centreonbroker_cfg_path, centreonbroker_module_path, centreonconnector_path, init_script_snmptt) VALUES ('$POLLER_NAME', '0',  '$POLLER_IP', '22', '/usr/bin/nagios',  '/usr/bin/nagiostats', '/var/log/nagios/service-perfdata', '/etc/init.d/nagios',  '1', 'NAGIOS', '/etc/centreon-broker', '/usr/share/centreon/lib/centreon-broker', NULL, '/etc/init.d/snmptt')"
    verbose_log "query: $query"
    $(echo $query | /usr/bin/mysql -h $MYSQL_DB_ADDRESS -u $CENTREON_DB_USER -p$CENTREON_DB_PASSWORD -D $CENTREON_DB_NAME)
    
    
    verbose_log "Get new poller ID"
    query2="SELECT id FROM nagios_server WHERE name = '$POLLER_NAME' AND ns_ip_address = '$POLLER_IP' LIMIT 1"
    verbose_log "query: $query2"
    result2=$(echo $query2 | /usr/bin/mysql -h $MYSQL_DB_ADDRESS -u $CENTREON_DB_USER -p$CENTREON_DB_PASSWORD -D $CENTREON_DB_NAME)
    
    POLLER_ID=`echo $result2 | awk {'print $NF'}`
    verbose_log "New poller find : $POLLER_ID !"
    
    verbose_log "Create new ndomod in centreon"
    query3="INSERT INTO cfg_ndomod (description, ns_nagios_server, instance_name, output_type, output, buffer_file, tcp_port, output_buffer_items, file_rotation_interval, file_rotation_command, file_rotation_timeout, reconnect_interval, reconnect_warning_interval, data_processing_options, config_output_options, activate) VALUES ('$POLLER_NAME', '$POLLER_ID',  '$NDO_INSTANCE_NAME',  'tcpsocket',  '$CENTRAL_IP',  NULL, '5668',  '5000',  '14400',  NULL, '60',  '15',  '900',  '-1',  '3',  '1')"
    verbose_log "query: $query3"
    $(echo $query3 | /usr/bin/mysql -h $MYSQL_DB_ADDRESS -u $CENTREON_DB_USER -p$CENTREON_DB_PASSWORD -D $CENTREON_DB_NAME)
    
    
    verbose_log "Create a new basic nagios.cfg for this new poller"
    ### centreon 2.2.X
    #query4="INSERT INTO cfg_nagios VALUES (NULL, '$POLLER_NAME', '/var/log/nagios/nagios.log', '/etc/nagios/', NULL, NULL, '/var/log/nagios/nagios.tmp', NULL, '/var/log/nagios/status.dat', NULL, NULL, '/usr/bin/p1.pl', NULL, 'nagios', 'nagios', '1', '1', '1', '2', '2', '1', 'd', '/var/log/nagios/archives/', '1', '1s', '/var/log/nagios/rw/nagios.cmd', NULL, NULL, '/var/log/nagios/nagios.pid', '1', '/var/log/nagios/status.sav', 60, '1', '1', '0', '1', '1', '1', '1', '1', '1', '2', NULL, NULL, '1', 's', NULL, 's', 200, 5, NULL, 5, 60, '2', NULL, NULL, '0', '25.0', '50.0', '25.0', '50.0', '0', 60, 10, 30, 30, 5, 5, 5, '0', NULL, '2', NULL, '1', NULL, 41, NULL, '/var/log/nagios/service-perfdata', NULL, NULL, '2', '2', NULL, NULL, NULL, NULL, '0', '1', NULL, NULL, '2', NULL, 'euro', '~!$%^&amp;*&quot;|&#039;&lt;&gt;?,()=', '\`~$^&amp;&quot;|&#039;&lt;&gt;', '2', '2', 'admin', 'admin@localhost', '$POLLER_NAME Nagios.cfg', '1', '/usr/lib/nagios/ndomod.o config_file=/etc/nagios/ndomod.cfg', '259967', NULL, '$POLLER_ID', '2', '2', NULL, NULL, '2', '2', '2', '2', NULL, '2', '2', NULL, 0, '0', '2', NULL, NULL, NULL, NULL, '0')"
    ### centreon 2.3.X
    ##query4="INSERT INTO cfg_nagios VALUES (NULL, '$POLLER_NAME', '/var/log/nagios/nagios.log', '/etc/nagios/', NULL, NULL, '/var/log/nagios/nagios.tmp', NULL, NULL, NULL, NULL, '/usr/bin/p1.pl', NULL, 'nagios', 'nagios', '1', '1', '1', '2', '2', '1', 'd', '/var/log/nagios/archives/', '1', '1s', '/var/log/nagios/rw/nagios.cmd', NULL, NULL, '/var/log/nagios/nagios.pid', '1', '/var/log/nagios/status.sav', 60, '1', '1', '0', '1', '1', '1', '1', '1', '1', '2', NULL, NULL, '1', 's', NULL, 's', 200, 5, NULL, 5, 60, '2', NULL, NULL, '0', '25.0', '50.0', '25.0', '50.0', '0', 60, 10, 30, 30, 5, 5, 5, '0', NULL, '2', NULL, '1', NULL, 41, NULL, '/var/log/nagios/service-perfdata', NULL, NULL, '2', '2', NULL, NULL, NULL, NULL, '0', '1', NULL, NULL, '2', NULL, 'euro', '~!$%^&amp;*&quot;|&#039;&lt;&gt;?,()=', '\`~$^&amp;&quot;|&#039;&lt;&gt;', '2', '2', 'admin', 'admin@localhost', '$POLLER_NAME Nagios.cfg', '1', '259967', NULL, '$POLLER_ID', '2', '2', NULL, NULL, '2', '2', '2', '2', NULL, '2', '2', NULL, 0, '0', '2', NULL, NULL, NULL, NULL, '0')"
    ### centreon 2.4.0
    query4="INSERT INTO cfg_nagios (nagios_name, log_file, cfg_dir, object_cache_file, precached_object_file, temp_file, temp_path, status_file, check_result_path, max_check_result_file_age, p1_file, status_update_interval, nagios_user, nagios_group, enable_notifications, execute_service_checks, accept_passive_service_checks, execute_host_checks, accept_passive_host_checks, enable_event_handlers, log_rotation_method, log_archive_path, check_external_commands, command_check_interval, command_file, downtime_file, comment_file, lock_file, retain_state_information, state_retention_file, retention_update_interval, use_retained_program_state, use_retained_scheduling_info, retained_contact_host_attribute_mask, retained_contact_service_attribute_mask, retained_process_host_attribute_mask, retained_process_service_attribute_mask, retained_host_attribute_mask, retained_service_attribute_mask, use_syslog, log_notifications, log_service_retries, log_host_retries, log_event_handlers, log_initial_states, log_external_commands, log_passive_checks, global_host_event_handler, global_service_event_handler, sleep_time, service_inter_check_delay_method, host_inter_check_delay_method, service_interleave_factor, max_concurrent_checks, max_service_check_spread, max_host_check_spread, check_result_reaper_frequency, max_check_result_reaper_time, interval_length, auto_reschedule_checks, auto_rescheduling_interval, auto_rescheduling_window, enable_flap_detection, low_service_flap_threshold, high_service_flap_threshold, low_host_flap_threshold, high_host_flap_threshold, soft_state_dependencies, service_check_timeout, host_check_timeout, event_handler_timeout, notification_timeout, ocsp_timeout, ochp_timeout, perfdata_timeout, obsess_over_services, ocsp_command, obsess_over_hosts, ochp_command, process_performance_data, host_perfdata_command, service_perfdata_command, host_perfdata_file, service_perfdata_file, host_perfdata_file_template, service_perfdata_file_template, host_perfdata_file_mode, service_perfdata_file_mode, host_perfdata_file_processing_interval, service_perfdata_file_processing_interval, host_perfdata_file_processing_command, service_perfdata_file_processing_command, check_for_orphaned_services, check_service_freshness, service_freshness_check_interval, freshness_check_interval, check_host_freshness, host_freshness_check_interval, date_format, illegal_object_name_chars, illegal_macro_output_chars, use_regexp_matching, use_true_regexp_matching, admin_email, admin_pager, nagios_comment, nagios_activate, event_broker_options, translate_passive_host_checks, nagios_server_id, enable_predictive_host_dependency_checks, enable_predictive_service_dependency_checks, cached_host_check_horizon, cached_service_check_horizon, use_large_installation_tweaks, free_child_process_memory, child_processes_fork_twice, enable_environment_macros, additional_freshness_latency, enable_embedded_perl, use_embedded_perl_implicitly, debug_file, debug_level, debug_level_opt, debug_verbosity, max_debug_file_size, daemon_dumps_core, passive_host_checks_are_soft, check_for_orphaned_hosts, external_command_buffer_slots, use_aggressive_host_checking, cfg_file) VALUES ('$POLLER_NAME','/var/log/nagios/nagios.log','/etc/nagios/',NULL,NULL,'/var/log/nagios/nagios.tmp',NULL,NULL,NULL,NULL,'/usr/bin/p1.pl',NULL,'nagios','nagios','1','1','1','2','2','1','d','/var/log/nagios/archives/','1','1s','/var/log/nagios/rw/nagios.cmd',NULL,NULL,'/var/log/nagios/nagios.pid','1','/var/log/nagios/status.sav',60,'1','1',NULL,NULL,NULL,NULL,NULL,NULL,'0','1','1','1','1','1','1','2',NULL,NULL,'1','s',NULL,'s',200,5,NULL,5,NULL,60,'2',NULL,NULL,'0','25.0','50.0','25.0','50.0','0',60,10,30,30,5,5,5,'0',NULL,'2',NULL,'1',NULL,41,NULL,'/var/log/nagios/service-perfdata',NULL,NULL,'2','2',NULL,NULL,NULL,NULL,'0','1',NULL,NULL,'2',NULL,'euro','~!$%^&amp;*&quot;|&#039;&lt;&gt;?,()=','\`~$^&amp;&quot;|&#039;&lt;&gt;','2','2','admin','admin@localhost','$POLLER_NAME Nagios.cfg','1','259967',NULL,'$POLLER_ID','2','2',NULL,NULL,'2','2','2','2',NULL,'2','2',NULL,0,'0','2',NULL,'0',NULL,'0',NULL,'0','nagios.cfg')"
    verbose_log "query: $query4"
    $(echo $query4 | /usr/bin/mysql -h $MYSQL_DB_ADDRESS -u $CENTREON_DB_USER -p$CENTREON_DB_PASSWORD -D $CENTREON_DB_NAME)

    verbose_log "Get new nagios ID in cfg_nagios"
    query5="SELECT nagios_id FROM cfg_nagios WHERE nagios_name = '$POLLER_NAME' LIMIT 1"
    verbose_log "query: $query5"
    result5=$(echo $query5 | /usr/bin/mysql -h $MYSQL_DB_ADDRESS -u $CENTREON_DB_USER -p$CENTREON_DB_PASSWORD -D $CENTREON_DB_NAME)
    NAGIOS_ID=`echo $result5 | awk {'print $NF'}`
    verbose_log "New Nagios ID find : $NAGIOS_ID !"

    verbose_log "Create new cfg_nagios_bkmod in centreon"
    query6="INSERT INTO cfg_nagios_broker_module (cfg_nagios_id, broker_module) VALUES ('$NAGIOS_ID','/usr/lib/nagios/ndomod.o config_file=/etc/nagios/ndomod.cfg')"
    verbose_log "query: $query6"
    $(echo $query6 | /usr/bin/mysql -h $MYSQL_DB_ADDRESS -u $CENTREON_DB_USER -p$CENTREON_DB_PASSWORD -D $CENTREON_DB_NAME)
    
    verbose_log "Create new cfg_cgi in centreon"
    query7="INSERT INTO cfg_cgi (cgi_name, instance_id, main_config_file, physical_html_path, url_html_path, nagios_check_command, use_authentication, default_user_name, authorized_for_system_information, authorized_for_system_commands, authorized_for_configuration_information, authorized_for_all_hosts, authorized_for_all_host_commands, authorized_for_all_services, authorized_for_all_service_commands, statusmap_background_image, default_statusmap_layout, statuswrl_include, default_statuswrl_layout, refresh_rate, host_unreachable_sound, host_down_sound, service_critical_sound, service_warning_sound, service_unknown_sound, ping_syntax, cgi_comment, cgi_activate, action_url_target, escape_html_tags, lock_author_names, notes_url_target) VALUES ('$POLLER_NAME','$POLLER_ID','/etc/nagios/nagios.cfg','/usr/share/nagios','/nagios','/usr/lib/nagios/plugins/check_nagios /var/log/nagios/status.dat 5 &#039;/usr/bin/nagios&#039;','1','nagiosadmin','nagiosadmin','nagiosadmin','nagiosadmin','nagiosadmin','nagiosadmin','nagiosadmin','nagiosadmin','logofullsize.jpg','4',NULL,'4',90,NULL,NULL,NULL,NULL,NULL,'/bin/ping -n -c 5 \$HOSTADDRESS\$','CGI for $POLLER_NAME','1',NULL,'2','2',NULL)"
    verbose_log "query: $query7"
    $(echo $query7 | /usr/bin/mysql -h $MYSQL_DB_ADDRESS -u $CENTREON_DB_USER -p$CENTREON_DB_PASSWORD -D $CENTREON_DB_NAME)
    
    echo "Add a new backend in $NAGVIS_INI"
    verbose_log "Add a new backend in $NAGVIS_INI"
    cat >> $NAGVIS_INI << EOF
[backend_ndomy_$POLLER_NAME]
backendtype="ndomy"
dbhost="$MYSQL_DB_ADDRESS"
dbname="$NAGIOS_DB_NAME"
dbuser="$CENTREON_DB_USER"
dbpass="$CENTREON_DB_PASSWORD"
dbinstancename="$POLLER_NAME"
maxtimewithoutupdate=360
EOF

    echo "Restart centcore"
    verbose_log "Restart centcore"
    /etc/init.d/centcore stop 2>/dev/null
    # Check centcore status
    centcore_pid=$(ps -ef | grep centcore | grep -v grep | awk -F " " '{print $2}')
    if let $centcore_pid 2>/dev/null
    then
        verbose_log "Force to kill centcore $centcore_pid"
        kill -9 $centcore_pid 2> /dev/null
    fi
    /etc/init.d/centcore start 2>/dev/null
fi
