#!/usr/bin/env bash
echo "********************************************************"
echo -e "*****\033[32mWelcome to asterCC cluster configuration shell\033[0m*****"
echo -e "*****\033[32mPlease follow the instructions to configure\033[0m********"
echo "********************************************************"

curuser=`whoami`
if [ ${curuser} != "root" ]
then
  echo -e "\033[31mmust be root user \033[0m"
  exit
fi

curpath=`pwd`
while :
do
    echo 'Please select to configure HA or cluster:'
    echo 1:HA
    echo 2:Cluster
    read confstatus
    if [ "$confstatus" = "1" ];then
        confstatus="HA"
        break
    elif [ "$confstatus" = "2" ];then
        confstatus="Cluster"
        break
    else
        continue
    fi
done
echo $confstatus

mainparmstr="serviceip servicemask servicegateway masterhostname masterip mastereth mastersshport slavehostname slaveip slaveeth slavesshport";
function getMainInfo(){
    echo -n "Please set service ip: "
    read serviceip
    echo -n "Please assign service netmask: "
    read servicemask
    echo -n "Please assign service gateway: "
    read servicegateway
    echo -e "\033[42;37m------------Set Master server infomation-------------------\033[0m"
    echo -n "Please assign master hostname: "
    read masterhostname
    echo -n "Please assign master heartbeat ip: "
    read masterip
    echo -n "Please assign master service ethernet device: "
    read mastereth
    echo -n "Please assign master server ssh port: "
    read mastersshport
    echo -n "Please assign mail address for sender: "
    read mailfrom 
    echo -n "Please assign mail address for receiver: "
    read mailto 
    
    echo -e "\033[42;37m------------Set Slave server infomation-------------------\033[0m"
    echo -n "Please assign slave hostname: "
    read slavehostname
    echo -n "Please assign slave heartbeat ip: "
    read slaveip
    echo -n "Please assign slave service ethernet device: "
    read slaveeth
    echo -n "Please assign slave server ssh port: "
    read slavesshport

    echo -e "\033[42;37m------------Set cluster server infomation-------------------\033[0m"
    cs=1
    csstr=""
    if [ "$confstatus" = "Cluster" ];then
        echo -n $csstr > $curpath/cccs.txt
        while :
        do
            echo -n "Please assign cluster server $cs hostname: "
            read csname
            echo -n "Please assign cluster server $cs ip: "
            read csip
            echo -n "Please assign cluster server $cs ssh port: "
            read cssshport
            echo "$csname $csip $cssshport" >> $curpath/cccs.txt
            let "cs=$cs+1"

            echo -en "\033[33mIf have other cluster server, press y to contiue, else press any other key to next step:\033[0m"
            read morecs
            if [ "$morecs" = "y" ];then
                continue
            else
                break
            fi
        done
    fi

    dbname=`sed -n '/\[database\]/,/\[asterisk\]/p' /etc/astercc.conf |grep dbname[\ ]*= |grep -v "^[\ *\;\ *]" |head -n 1 |cut -d= -f2 |tr -d " "`
    dbuser=`sed -n '/\[database\]/,/\[asterisk\]/p' /etc/astercc.conf |grep username[\ ]*= |grep -v "^[\ *\;\ *]" |head -n 1 |cut -d= -f2 |tr -d " "`
    dbpasswd=`sed -n '/\[database\]/,/\[asterisk\]/p' /etc/astercc.conf |grep password[\ ]*= |grep -v "^[\ *\;\ *]" |head -n 1 |cut -d= -f2 |tr -d " "`
    amiuser=`sed -n '/\[asterisk\]/,/\[system\]/p' /etc/astercc.conf |grep username[\ ]*= |grep -v "^[\ *\;\ *]" |head -n 1 |cut -d= -f2 |tr -d " "`
    amisecret=`sed -n '/\[asterisk\]/,/\[system\]/p' /etc/astercc.conf |grep secret[\ ]*= |grep -v "^[\ *\;\ *]" |head -n 1 |cut -d= -f2 |tr -d " "`


    serviceipsed1=`echo ${serviceip} |cut -d "." -f1`
    serviceipsed2=`echo ${serviceip} |cut -d "." -f2`
    serviceipsed3=`echo ${serviceip} |cut -d "." -f3`
    serviceipsed="${serviceipsed1}.${serviceipsed2}.${serviceipsed3}"

    heartbeatipsed1=`echo ${masterip} |cut -d "." -f1`
    heartbeatipsed2=`echo ${masterip} |cut -d "." -f2`
    heartbeatipsed3=`echo ${masterip} |cut -d "." -f3`
    heartbeatipsed="${heartbeatipsed1}.${heartbeatipsed2}.${heartbeatipsed3}"
 
    mainparmvalue="${serviceip// /} ${servicemask// /} ${servicegateway// /} ${masterhostname// /} ${masterip// /} ${mastereth// /} ${mastersshport// /} ${slavehostname// /} ${slaveip// /} ${slaveeth// /} ${slavesshport// /}";
}



function configureMysqlconf(){
    echo -e "\033[32mconfigure database sync...\033[0m"
    sleep 2
    cat > /etc/my.cnf << EOF
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql
# Default to using old password format for compatibility with mysql 3.x
# clients (those using the mysqlclient10 compatibility package).
#old_passwords=1

log-bin=mysql-bin
max_binlog_size = 1024M
expire-logs-days = 15
binlog_cache_size = 4M
max_binlog_cache_size = 512M
server-id = 1
binlog-do-db=${dbname}
binlog-ignore-db=mysql
replicate-do-db=${dbname}
replicate-ignore-db=mysql
log-slave-updates
slave-skip-errors=all
sync_binlog=1
auto_increment_increment=2
auto_increment_offset=1

# Disabling symbolic-links is recommended to prevent assorted security risks;
# to do so, uncomment this line:
# symbolic-links=0
### skip-name-resolve
skip-external-locking
### table_open_cache = 1024


## MyISAM Engine
key_buffer_size = 384M
myisam_sort_buffer_size         = 128M  #index buffer size for creating/altering indexes
myisam_max_sort_file_size       = 256M  #max file size for tmp table when creating/alering indexes
myisam_repair_threads           = 4     #thread quantity when running repairs
myisam_recover                  = BACKUP        #repair mode, recommend BACKUP

## Connections
max_connections = 4096
max_connect_errors              = 100   #default: 10
concurrent_insert               = 2     #default: 1, 2: enable insert for all instances
connect_timeout                 = 30    #default -5.1.22: 5, +5.1.22: 10
max_allowed_packet              = 64M   #max size of incoming data to allow

## Thread settings
### thread_concurrency = 16
### thread_cache_size               = 200 #recommend 5% of max_connections

## Per-Thread Buffers * (max_connections) = total per-thread mem usage
thread_stack                    = 256K    #default: 32bit: 192K, 64bit: 256K
sort_buffer_size                = 512K    #default: 2M, larger may cause perf issues
read_buffer_size                = 512K    #default: 128K, change in increments of 4K
read_rnd_buffer_size            = 512K    #default: 256K
join_buffer_size                = 512K    #default: 128K
binlog_cache_size               = 64K     #default: 32K, size of buffer to hold TX queries


query_cache_size = 32M
query_cache_limit = 512K

max_heap_table_size = 1G
bulk_insert_buffer_size = 1G
tmp_table_size = 1G

wait_timeout = 180000
### long_query_time=1
### log-slow-queries=/var/log/mysqld_slow.log

innodb_file_per_table = 1
innodb_table_locks = 0
innodb_log_buffer_size          = 128M  #global buffer
#innodb_log_file_size = 16M
innodb_lock_wait_timeout        = 60
innodb_thread_concurrency       = 4    #recommend 2x core quantity
innodb_commit_concurrency       = 4    #recommend 4x num disks
skip-innodb-doublewrite

### innodb_buffer_pool_size = 1024M         #recommend 70-80% of the memory if it's dedicated for mysql
### innodb_stats_on_metadata = 0

init-file=/var/lib/mysql/db-init.sql

[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
EOF
    service mysqld restart
    scp -P${slavesshport} /etc/my.cnf ${slavehostname}:/etc/my.cnf
    ssh -p${slavesshport} ${slavehostname} sed -i 's/server-id.*/server-id=2/' /etc/my.cnf
    ssh -p${slavesshport} ${slavehostname} sed -i 's/auto_increment_offset.*/auto_increment_offset=2/' /etc/my.cnf
    ssh -p${slavesshport} ${slavehostname} service mysqld restart
    
    dbmasterposstr=`mysql -p${dbpasswd} -e "show master status"`
    dbmasterpos=`echo $dbmasterposstr |cut -d " " -f6`
    dbmasterfile=`echo $dbmasterposstr |cut -d " " -f5`
    
    if [ $dbmasterfile == "Executed_Gtid_Set" ]
    then
        dbmasterpos=`echo $dbmasterposstr |cut -d " " -f7`
        dbmasterfile=`echo $dbmasterposstr |cut -d " " -f6`
    fi
    mysqldump --opt -u${dbuser} -p${dbpasswd} ${dbname} > ${dbname}.sql
    scp -P${slavesshport} ${dbname}.sql ${slavehostname}:${dbname}.sql
    

    mysql -u${dbuser} -p${dbpasswd} -e "GRANT ALL PRIVILEGES ON ${dbname}.* to '${dbuser}'@'${serviceipsed}.%' identified by '${dbpasswd}'";
    ssh -p${slavesshport} ${slavehostname} "mysql -u${dbuser} -p${dbpasswd} -e \"GRANT ALL PRIVILEGES ON ${dbname}.* to '${dbuser}'@'${serviceipsed}.%' identified by '${dbpasswd}'\"";

    mysql -u${dbuser} -p${dbpasswd} -e "GRANT REPLICATION SLAVE ON *.* to '${dbuser}rep'@'${heartbeatipsed}.%' identified by '${dbpasswd}.rep';FLUSH PRIVILEGES";
    ssh -p${slavesshport} ${slavehostname} "mysql -u${dbuser} -p${dbpasswd} -e \"GRANT REPLICATION SLAVE ON *.* to '${dbuser}rep'@'${heartbeatipsed}.%' identified by '${dbpasswd}.rep';FLUSH PRIVILEGES\"";
    
    ssh -p${slavesshport} ${slavehostname} "mysql -u${dbuser} -p${dbpasswd} ${dbname} < /root/${dbname}.sql" 
    sdbmasterposstr=`ssh -p${slavesshport} ${slavehostname} "mysql -u${dbuser} -p${dbpasswd} -e \"show master status\""`
    sdbmasterpos=`echo $sdbmasterposstr|cut -d " " -f6`
    sdbmasterfile=`echo $sdbmasterposstr|cut -d " " -f5`

    if [ $sdbmasterfile == "Executed_Gtid_Set" ]
    then
        sdbmasterpos=`echo $sdbmasterposstr |cut -d " " -f7`
        sdbmasterfile=`echo $sdbmasterposstr |cut -d " " -f6`
    fi
    mysql -u${dbuser} -p${dbpasswd} -e "stop slave;CHANGE master to master_host='${slaveip}',master_user='${dbuser}rep',master_password='${dbpasswd}.rep',master_log_file='${sdbmasterfile}',master_log_pos=${sdbmasterpos};start slave;"
    ssh -p${slavesshport} ${slavehostname} "mysql -u${dbuser} -p${dbpasswd} -e \"stop slave; CHANGE master to master_host='${masterip}',master_user='${dbuser}rep',master_password='${dbpasswd}.rep',master_log_file='${dbmasterfile}',master_log_pos=${dbmasterpos};start slave;\"" 

}

function configRsync(){
    echo -e "\033[32mconfigure file sync...\033[0m"
    sleep 2
    cat > /etc/rsyncd.conf << EOF
uid=asterisk
gid=asterisk
use chroot=no
max connections=10
pid file = /var/run/rsyncd.pid
lock file = /var/run/rsync.lock
log file = /var/log/rsyncd.log
secrets file = /etc/rsyncd/server.pass

[ccsync]
path = /home/ccsync
commet = stest file
ignore errors
read only = no
write only = no
hosts allow =${heartbeatipsed}.0/24
hosts deny = *
list = false
uid = asterisk
gid = asterisk
auth users = ccsync
EOF

    mkdir -p /etc/rsyncd/
    echo ccsync:temp123 > /etc/rsyncd/server.pass
    echo temp123 > /etc/rsyncd/${slavehostname}.pass
    echo temp123 > /etc/rsyncd/cluster.pass
    chmod 600 -R /etc/rsyncd
    echo "/usr/bin/rsync --daemon" >> /etc/rc.local
    /usr/bin/rsync --daemon
   
    scp -P${slavesshport} /etc/rsyncd.conf ${slavehostname}:/etc/
    ssh -p${slavesshport} ${slavehostname} "mkdir -p /etc/rsyncd"
    ssh -p${slavesshport} ${slavehostname} "echo ccsync:temp123 > /etc/rsyncd/server.pass"
    ssh -p${slavesshport} ${slavehostname} "echo temp123 > /etc/rsyncd/${masterhostname}.pass"
    ssh -p${slavesshport} ${slavehostname} "echo temp123 > /etc/rsyncd/cluster.pass"
    ssh -p${slavesshport} ${slavehostname} "chmod 600 -R /etc/rsyncd"
    ssh -p${slavesshport} ${slavehostname} "/usr/bin/rsync --daemon"
    ssh -p${slavesshport} ${slavehostname} "echo \"/usr/bin/rsync --daemon\" >> /etc/rc.local"

    webdirstr=`sed -n '/\[system\]/,/\[*.*\]/p' /etc/astercc.conf |grep apppath[\ ]*= |grep -v "^[\ *\;\ *]" |head -n 1 |cut -d= -f2 |tr -d " "`
    webdirstr=${webdirstr// /}
    webdir=${webdirstr//\/app/}
    webdirstr=${webdirstr//\// }
    i=0

    for p in ${webdirstr[@]}
    do
        let "i=$i+1";
    done
    let "i=$i-1";
    webdirname=`echo $webdirstr |cut -d " " -f$i`
    if [ ! -d /home/ccsync ];then
        sed -i 's/permit=.*/&\npermit='${serviceipsed}'.0\/'${servicemask}'\npermit='${heartbeatipsed}'.0\/255.255.255.0/' /etc/asterisk/manager.conf
        mkdir /home/ccsync/
        cd /home/ccsync/
        mv /etc/asterisk/ ./
        ln -s /home/ccsync/asterisk/   /etc/asterisk
        if [ -L /var/lib/asterisk/mohmp3 ];then
            rm /var/lib/asterisk/mohmp3
            cp -Rp /var/lib/asterisk/moh/ /var/lib/asterisk/mohmp3
        fi
        mv /var/lib/asterisk/mohmp3  ./
        ln -s /home/ccsync/mohmp3/   /var/lib/asterisk/mohmp3
        mv /var/lib/asterisk/moh /var/lib/asterisk/moh.bak
        ln -s /home/ccsync/mohmp3/   /var/lib/asterisk/moh
        mv /var/lib/asterisk/sounds/  ./
        ln -s /home/ccsync/sounds/  /var/lib/asterisk/sounds
        mv /opt/asterisk/scripts/astercc/  ./
        ln -s /home/ccsync/astercc/  /opt/asterisk/scripts/astercc
        mv ${webdir}  ./
        ln -s /home/ccsync/${webdirname}/ ${webdir}
        mv /etc/iaxmodem/  ./
        ln -s /home/ccsync/iaxmodem/  /etc/iaxmodem 
        ln /usr/bin/inotifywait /usr/local/bin/
        cd ${curpath}
        
        scp -r -P${slavesshport}  /home/ccsync/ ${slavehostname}:/home

        ssh -p${slavesshport} ${slavehostname} "chown asterisk.asterisk /home/ccsync -R"
        ssh -p${slavesshport} ${slavehostname} "mv /etc/asterisk/   /etc/asterisk.bak"
        ssh -p${slavesshport} ${slavehostname} "ln -s /home/ccsync/asterisk/   /etc/asterisk"
        ssh -p${slavesshport} ${slavehostname} "cp ${webdir}/app/views/agents/agentsxindesk.ctp /home/ccsync/${webdirname}/app/views/agents/"
        ssh -p${slavesshport} ${slavehostname} "cp /opt/asterisk/scripts/astercc/*.astercc /home/ccsync/astercc"
        ssh -p${slavesshport} ${slavehostname} "mv ${webdir} ${webdir}.bak"
        ssh -p${slavesshport} ${slavehostname} "ln -s /home/ccsync/${webdirname} ${webdir}"
        ssh -p${slavesshport} ${slavehostname} "mv /var/lib/asterisk/mohmp3 /var/lib/asterisk/mohmp3.bak"
        ssh -p${slavesshport} ${slavehostname} "mv /var/lib/asterisk/moh /var/lib/asterisk/moh.bak"
        ssh -p${slavesshport} ${slavehostname} "ln -s /home/ccsync/mohmp3/ /var/lib/asterisk/"
        ssh -p${slavesshport} ${slavehostname} "ln -s /home/ccsync/mohmp3/ /var/lib/asterisk/moh"
        ssh -p${slavesshport} ${slavehostname} "mv /var/lib/asterisk/sounds/ /var/lib/asterisk/sounds.bak"
        ssh -p${slavesshport} ${slavehostname} "ln -s /home/ccsync/sounds/ /var/lib/asterisk/"
        ssh -p${slavesshport} ${slavehostname} "mv /opt/asterisk/scripts/astercc/ /opt/asterisk/scripts/astercc.bak"
        ssh -p${slavesshport} ${slavehostname} "ln -s /home/ccsync/astercc/ /opt/asterisk/scripts/"
        ssh -p${slavesshport} ${slavehostname} "mv  /etc/iaxmodem  /etc/iaxmodem.bak"
        ssh -p${slavesshport} ${slavehostname} "ln -s  /home/ccsync/iaxmodem /etc/"
        ssh -p${slavesshport} ${slavehostname} "ln /usr/bin/inotifywait /usr/local/bin/"

        if [ "$confstatus" = "Cluster" ];then
            echo ${slavehostname} > /opt/asterisk/scripts/astercc/astcc_rsynclist.conf
            ssh -p${slavesshport} ${slavehostname} "echo ${masterhostname} > /opt/asterisk/scripts/astercc/astcc_rsynclist.conf"
            cat $curpath/cccs.txt | while read cslines
            do
                cshostname=`echo $cslines |cut -d " " -f1`
                csip=`echo $cslines |cut -d " " -f2`
                cssshport=`echo $cslines |cut -d " " -f3`
                
                echo ${cshostname} >> /opt/asterisk/scripts/astercc/astcc_rsynclist.conf
                ssh -p${slavesshport} ${slavehostname} "echo ${cshostname} >> /opt/asterisk/scripts/astercc/astcc_rsynclist.conf"
 
                scp -r -P${cssshport}  /home/ccsync/ ${cshostname}:/home

                ssh -p${cssshport} ${cshostname} "chown asterisk.asterisk /home/ccsync -R"
                ssh -p${cssshport} ${cshostname} "mv /etc/asterisk/   /etc/asterisk.bak"
                ssh -p${cssshport} ${cshostname} "ln -s /home/ccsync/asterisk/   /etc/asterisk"
                ssh -p${cssshport} ${cshostname} "cp ${webdir}/app/views/agents/agentsxindesk.ctp /home/ccsync/${webdirname}/app/views/agents/"
                ssh -p${cssshport} ${cshostname} "cp /opt/asterisk/scripts/astercc/*.astercc /home/ccsync/astercc"
                ssh -p${cssshport} ${cshostname} "mv ${webdir} ${webdir}.bak"
                ssh -p${cssshport} ${cshostname} "ln -s /home/ccsync/${webdirname} ${webdir}"
                ssh -p${cssshport} ${cshostname} "mv /var/lib/asterisk/mohmp3 /var/lib/asterisk/mohmp3.bak"
                ssh -p${cssshport} ${cshostname} "mv /var/lib/asterisk/moh /var/lib/asterisk/moh.bak"
                ssh -p${cssshport} ${cshostname} "ln -s /home/ccsync/mohmp3/ /var/lib/asterisk/"
                ssh -p${cssshport} ${cshostname} "ln -s /home/ccsync/mohmp3/ /var/lib/asterisk/moh"
                ssh -p${cssshport} ${cshostname} "mv /var/lib/asterisk/sounds/ /var/lib/asterisk/sounds.bak"
                ssh -p${cssshport} ${cshostname} "ln -s /home/ccsync/sounds/ /var/lib/asterisk/"
                ssh -p${cssshport} ${cshostname} "mv /opt/asterisk/scripts/astercc/ /opt/asterisk/scripts/astercc.bak"
                ssh -p${cssshport} ${cshostname} "ln -s /home/ccsync/astercc/ /opt/asterisk/scripts/"
                ssh -p${cssshport} ${cshostname} "mv  /etc/iaxmodem  /etc/iaxmodem.bak"
                ssh -p${cssshport} ${cshostname} "ln -s  /home/ccsync/iaxmodem /etc/"
                ssh -p${cssshport} ${cshostname} "ln /usr/bin/inotifywait /usr/local/bin/"

                scp -P${cssshport} /etc/rsyncd.conf ${cshostname}:/etc/
                ssh -p${cssshport} ${cshostname} "sed -i 's/hosts allow.*/hosts allow = '${serviceipsed}'.0\/24/' /etc/rsyncd.conf"
                ssh -p${cssshport} ${cshostname} "mkdir -p /etc/rsyncd"
                ssh -p${cssshport} ${cshostname} "echo ccsync:temp123 > /etc/rsyncd/server.pass"
                ssh -p${cssshport} ${cshostname} "echo temp123 > /etc/rsyncd/${masterhostname}.pass"
                ssh -p${cssshport} ${cshostname} "chmod 600 -R /etc/rsyncd"
                ssh -p${cssshport} ${cshostname} "/usr/bin/rsync --daemon"
                ssh -p${cssshport} ${cshostname} "echo \"/usr/bin/rsync --daemon\" >> /etc/rc.local"
            done
        fi
    fi
}

function configureHAconf(){
    echo -e "\033[32mconfigure ha.conf...\033[0m"
    sleep 2
    #get productserial
    echo "------get $masterhostname productserial-----------------"
    `/opt/asterisk/scripts/astercc/asterccc -l > ./curlic 2>&1`

    isseria=no
    for line in $(<./curlic)
    do
        if [ "$isseria" = "yes" ];then
            curseria=$line
            isseria=no
            break
        fi
        if [ "$line" = "Serial:" ];then
            isseria=yes
        fi
    done
    echo "------get $slavehostname productserial-----------------"
    ssh -p${slavesshport} ${slavehostname} "/opt/asterisk/scripts/astercc/asterccc -l > /root/${slavehostname}.lic 2>&1"
    scp -P${slavesshport} ${slavehostname}:${slavehostname}.lic ./
    
    isseria=no
    for line in $(<./${slavehostname}.lic)
    do
        if [ "$isseria" = "yes" ];then
            slaveseria=$line
            isseria=no
            break
        fi
        if [ "$line" = "Serial:" ];then
            isseria=yes
        fi
    done

    if [ "$confstatus" = "HA" ];then
    cat > /etc/asterccha.conf << EOF
[system]
debug=1
mailfrom = ${mailfrom}
mailto = ${mailto}

[main]
;nodelist 为节点列表，写对方的hostname
nodelist=${slavehostname}
;备份机间隔多少秒检测主机服务状态
interval=30
timeout=15
;cluster/HA
status = HA

[local]
;live/backup
node=${masterhostname}
;本机的产品序列号，可以执行/opt/asterisk/scripts/astercc/asterccc -l 查看
productserial=${curseria}
;属性，live为主，backup为备
status=live
;当本机为备机时，启动主备脚本，延迟多少秒后开始对主机服务状态检测，避免两台服务器同时启动时，出现误切换
checkstart=300
;本机ssh服务端口
sshport = ${mastersshport}
;服务ip
serviceip=${serviceip}
;服务虚拟网卡名
serviceeth=${mastereth}
;服务ip子网掩码
servicemask=${servicemask}
;以下为astercc相关4种服务，参数内容不要改动
http=nginx|php-fpm
database=mysqld
pbx=asterisk
cti=asterccd
;主备文件同步主目录
syncsrc=/home/ccsync/
;主备录音同步主目录
syncmonitor=/home/ccmonitor
;服务网卡所在网段的网关地址，用于确认本机网段是否正常，所以该网关需要允许本机的icmp，就是能被本机ping通。
gateway=${servicegateway}

;节点配置
[${slavehostname}]
;节点产品序列号
productserial=${slaveseria}
;心跳ip
heartbeatip=${slaveip}
;节点ssh服务端口
sshport = ${slavesshport}
;节点服务ip
serviceip=${serviceip}
;节点服务虚拟网卡名
serviceeth=${slaveeth}
;节点服务ip子网掩码
servicemask=${servicemask}
;http的最后一个|后的数字(表示请求几次http失败后，进行切换，默认是2次，不能为空)
http=nginx,php-fpm|80|2
database=mysqld|${dbname}|${dbuser}|${dbpasswd}
pbx=asterisk|5038|astercc|asterccsecret
cti=asterccd|4577
;rsync文件同步目标和用户名
syncdst=ccsync
syncuser=ccsync
EOF

cat > ./${slavehostname}.asterccha.conf << EOF
[system]
debug=1
mailfrom = ${mailfrom}
mailto = ${mailto}

[main]
nodelist=${masterhostname}
interval=30
timeout=15
;cluster/HA
status = HA

[local]
;live/backup
node=${slavehostname}
productserial=${slaveseria}
status=backup
checkstart=300
sshport = ${slavesshport}
serviceip=${serviceip}
serviceeth=${slaveeth}
servicemask=${servicemask}
http=nginx|php-fpm
database=mysqld
pbx=asterisk
cti=asterccd
syncsrc=/home/ccsync/
syncmonitor=/home/ccmonitor
gateway=${servicegateway}

[$masterhostname]
productserial=${curseria}
heartbeatip=${masterip}
sshport = ${mastersshport}
serviceip=${serviceip}
serviceeth=${mastereth}
servicemask=${servicemask}
;http的最后一个|后的数字(表示请求几次http失败后，进行切换，默认是2次，不能为空)
http=nginx,php-fpm|80|2
database=mysqld|${dbname}|${dbuser}|${dbpasswd}
pbx=asterisk|5038|astercc|asterccsecret
cti=asterccd|4577
syncdst=ccsync
syncuser=ccsync
EOF
else
    mnodelist=${slavehostname};
    snodelist=${masterhostname};
    cat $curpath/cccs.txt | while read cslines
    do
        cshostname=`echo $cslines |cut -d " " -f1`
        csip=`echo $cslines |cut -d " " -f2`
        cssshport=`echo $cslines |cut -d " " -f3`
        mnodelist="${mnodelist},${cshostname}"
        snodelist="${snodelist},${cshostname}"
    done

    cat > /etc/asterccha.conf << EOF
[system]
debug=1

[main]
;nodelist 为节点列表，写对方的hostname
nodelist=${mnodelist}
;备份机间隔多少秒检测主机服务状态
interval=30
timeout=15
;cluster/HA
status = MHA

[local]
;live/backup
node=${masterhostname}
productserial=${curseria}
status=live
checkstart=300
sshport = ${mastersshport}
serviceip=${serviceip}
serviceeth=${mastereth}
servicemask=${servicemask}
http=nginx|php-fpm
database=mysqld
;pbx=asterisk
;cti=asterccd
syncsrc=/home/ccsync/
syncmonitor=/home/ccmonitor
gateway=${servicegateway}
switchaction=astcc_datamover|astcc_dialer|astcc_autodialer|astcc_statistics|astcc_sysevents|cron

;节点配置
[${slavehostname}]
productserial=${slaveseria}
heartbeatip=${slaveip}
sshport = ${slavesshport}
serviceip=${serviceip}
serviceeth=${slaveeth}
servicemask=${servicemask}
http=nginx,php-fpm|80|2
database=mysqld|${dbname}|${dbuser}|${dbpasswd}
;pbx=asterisk|5038|astercc|asterccsecret
;cti=asterccd|4577
syncdst=ccsync
syncuser=ccsync
switchaction=astcc_datamover|astcc_dialer|astcc_autodialer|astcc_statistics|astcc_sysevents|cron
EOF

cat > ./${slavehostname}.asterccha.conf << EOF
[system]
debug=1

[main]
nodelist=${snodelist}
interval=30
timeout=15
;cluster/HA
status = MHA

[local]
;live/backup
node=${slavehostname}
productserial=${slaveseria}
status=backup
checkstart=300
sshport = ${slavesshport}
serviceip=${serviceip}
serviceeth=${slaveeth}
servicemask=${servicemask}
http=nginx|php-fpm
database=mysqld
;pbx=asterisk
;cti=asterccd
syncsrc=/home/ccsync/
syncmonitor=/home/ccmonitor
gateway=${servicegateway}
switchaction=astcc_datamover|astcc_dialer|astcc_autodialer|astcc_statistics|astcc_sysevents|cron

[$masterhostname]
productserial=${curseria}
heartbeatip=${masterip}
sshport = ${mastersshport}
serviceip=${serviceip}
serviceeth=${mastereth}
servicemask=${servicemask}
;http的最后一个|后的数字(表示请求几次http失败后，进行切换，默认是2次，不能为空)
http=nginx,php-fpm|80|2
database=mysqld|${dbname}|${dbuser}|${dbpasswd}
;pbx=asterisk|5038|astercc|asterccsecret
;cti=asterccd|4577
syncdst=ccsync
syncuser=ccsync
switchaction=astcc_datamover|astcc_dialer|astcc_autodialer|astcc_statistics|astcc_sysevents|cron
EOF
    fi
    if [ "$confstatus" = "Cluster" ];then
        sed -i '/var $default/,/encoding/s/'\'host\''.*/'\'host\'' => '\'${serviceip}\''\,/1' /home/ccsync/${webdirname}/app/config/database.php
        sed -i '/var $default/,/encoding/s/'\'login\''.*/'\'login\'' => '\'${dbuser}\''\,/1' /home/ccsync/${webdirname}/app/config/database.php
        sed -i '/var $default/,/encoding/s/'\'password\''.*/'\'password\'' => '\'${dbpasswd}\''\,/1' /home/ccsync/${webdirname}/app/config/database.php
        sed -i '/var $default/,/encoding/s/'\'database\''.*/'\'database\'' => '\'${dbname}\''\,/1' /home/ccsync/${webdirname}/app/config/database.php

        sed -i '/\[database\]/,/\[asterisk\]/s/dbhost.*/dbhost = '${serviceip}'/1' /etc/astercc.conf
        sed -i '/\[database\]/,/\[asterisk\]/s/dbname.*/dbname = '${dbname}'/1' /etc/astercc.conf
        sed -i '/\[database\]/,/\[asterisk\]/s/username.*/username = '${dbuser}'/1' /etc/astercc.conf
        sed -i '/\[database\]/,/\[asterisk\]/s/password.*/password = '${dbpasswd}'/1' /etc/astercc.conf

        sed -i '/\[asterisk\]/,/\[system\]/s/server.*/server = '${serviceip}'/1' /etc/astercc.conf

        sed -i '/\[statistics\]/,/\[asterccc\]/s/dbhost.*/dbhost = '${serviceip}'/1' /etc/astercc.conf
        sed -i '/\[statistics\]/,/\[asterccc\]/s/dbname.*/dbname = '${dbname}'/1' /etc/astercc.conf
        sed -i '/\[statistics\]/,/\[asterccc\]/s/dbuser.*/dbuser = '${dbuser}'/1' /etc/astercc.conf
        sed -i '/\[statistics\]/,/\[asterccc\]/s/dbpassword.*/dbpassword = '${dbpasswd}'/1' /etc/astercc.conf
        sed -i '/\[system\]/,/\[dialer\]/s/astccdialer.*/;&/g' /etc/astercc.conf
        sed -i '/\[system\]/,/\[dialer\]/s/astccautodialer.*/;&/g' /etc/astercc.conf
        sed -i '/\[system\]/,/\[dialer\]/s/astccdatamover.*/;&/g' /etc/astercc.conf
        sed -i '/\[system\]/,/\[dialer\]/s/astccstatistics.*/;&/g' /etc/astercc.conf
        sed -i '/\[system\]/,/\[dialer\]/s/astccsysevents.*/;&/g' /etc/astercc.conf
        scp -r -P${slavesshport}  /etc/astercc.conf ${slavehostname}:/etc/astercc.conf            
    fi


    if [ "$confstatus" = "Cluster" ];then
        cat $curpath/cccs.txt | while read cslines
        do
            cshostname=`echo $cslines |cut -d " " -f1`
            csip=`echo $cslines |cut -d " " -f2`
            cssshport=`echo $cslines |cut -d " " -f3`
            echo "------get $cshostname $csip $cssshport productserial-----------------"
            ssh -p${cssshport} ${cshostname} "/opt/asterisk/scripts/astercc/asterccc -l > /root/${cshostname}.lic 2>&1"
            scp -P${cssshport} ${cshostname}:${cshostname}.lic ./
            echo "-----------------------"
            isseria=no
            curcsseria=""
            
            for line in $(<./${cshostname}.lic)
            do
                if [ "$isseria" = "yes" ];then
                    curcsseria=$line
                    isseria=no
                    break
                fi
                if [ "$line" = "Serial:" ];then
                    isseria=yes
                fi
            done

            echo "[${cshostname}]" >> /etc/asterccha.conf 
            echo "[${cshostname}]" >> $curpath/${slavehostname}asterccha.conf 
            echo "productserial=${curcsseria}" >> /etc/asterccha.conf 
            echo "productserial=${curcsseria}" >> $curpath/${slavehostname}.asterccha.conf 
            echo "heartbeatip=${csip}" >> /etc/asterccha.conf 
            echo "heartbeatip=${csip}" >> $curpath/${slavehostname}.asterccha.conf 
            echo "sshport=${cssshport}" >> /etc/asterccha.conf 
            echo "sshport=${cssshport}" >> $curpath/${slavehostname}.asterccha.conf 

            ssh -p${cssshport} ${cshostname} "echo '' > /var/spool/cron/root"
            ssh -p${cssshport} ${cshostname} "service asterccd stop"
            ssh -p${cssshport} ${cshostname} "service nginx stop"
            ssh -p${cssshport} ${cshostname} "chkconfig nginx off"
            ssh -p${cssshport} ${cshostname} "service php-fpm stop"
            ssh -p${cssshport} ${cshostname} "chkconfig php-fpm off"
            ssh -p${cssshport} ${cshostname} "service mysqld stop"
            ssh -p${cssshport} ${cshostname} "chkconfig mysqld off"

            scp -r -P${cssshport}  /etc/astercc.conf ${cshostname}:/etc/astercc.conf
            ssh -p${cssshport} ${cshostname} "mkdir -p /home/ccmonitor"
            ssh -p${cssshport} ${cshostname} "chown asterisk.asterisk /home/ccmonitor"

        done
    fi

    scp -P${slavesshport} $curpath/${slavehostname}.asterccha.conf ${slavehostname}:/etc/asterccha.conf
    ssh -p${slavesshport} ${slavehostname} "echo \"/opt/asterisk/scripts/astercc/astcc_hacheck -d\" >> /etc/rc.local"
    mkdir -p /home/ccmonitor
    chown asterisk.asterisk /home/ccmonitor
    ssh -p${slavesshport} ${slavehostname} "mkdir -p /home/ccmonitor"
    ssh -p${slavesshport} ${slavehostname} "chown asterisk.asterisk /home/ccmonitor"

}

getMainInfo;

i=0

for p in ${mainparmstr[@]}
do
    let "i=$i+1";
done

for((pi=1;pi<=${i};pi++))
do
    confirmstr1=`echo $mainparmstr|cut -d " " -f$pi`
    confirmstr2=`echo $mainparmvalue|cut -d " " -f$pi`
    if [ "$confirmstr2" = "" ];then
        parmerror=1;
    fi
    echo "$confirmstr1: $confirmstr2"
done

if [ "$confstatus" = "Cluster" ];then
    cat $curpath/cccs.txt | while read cslines
    do
        echo $cslines
    done
fi

if [ "$parmerror" = "1" ];then
    echo -e "\033[31mall parameter have to fill \033[0m"
    exit;
else
    echo -e "\033[33mplease confirm above parameter, press y to continue \033[0m"
    echo -ne "\033[33mpress any other key to exit \033[0m"
    read ifcontinue
    if [ "$ifcontinue" = "y" ];then
        echo -e "\033[32mcontinue...\033[0m"
    else
        echo -e "\033[31mexit\033[0m"
        exit;
    fi
fi

ifconfig $mastereth $serviceip up netmask $servicemask
hostname ${masterhostname}
sed -i 's/HOSTNAME.*/HOSTNAME='${masterhostname}'/' /etc/sysconfig/network

echo "$masterip $masterhostname" >> /etc/hosts
echo "$slaveip $slavehostname" >> /etc/hosts
rm ~/.ssh -rf
ssh-keygen -t rsa -f ~/.ssh/id_rsa -P ''
#ssh-copy-id -i ~/.ssh/id_rsa.pub "-p${slavesshport} root@${slavehostname}"
cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
chmod 600 -R ~/.ssh

ssh -p${slavesshport} ${slavehostname} "mkdir -p /root/.ssh"
#khs=`cat ~/.ssh/known_hosts`
#khs=${khs//${slavehostname},${slaveip}/${masterhostname},${masterip}}
#echo ${khs} >> ~/.ssh/known_hosts
scp -P${slavesshport} ~/.ssh/*  ${slavehostname}:/root/.ssh
ssh -p${slavesshport} ${slavehostname} "chmod 600 -R /root/.ssh"

ssh -p${slavesshport} ${slavehostname} hostname ${slavehostname}
ssh -p${slavesshport} ${slaveip} sed -i 's/HOSTNAME.*/HOSTNAME='${slavehostname}'/' /etc/sysconfig/network
ssh -p${slavesshport} ${slavehostname} "echo $masterip $masterhostname >> /etc/hosts"
ssh -p${slavesshport} ${slavehostname} "echo $slaveip $slavehostname >> /etc/hosts"
ssh -t -p${slavesshport} ${slavehostname} "ssh -p${mastersshport} ${masterhostname} \"echo ${slavehostname} > /root/testssh\""

cat > /etc/sysconfig/iptables << EOF
*filter
:INPUT DROP [32888:6036616]
:FORWARD DROP [0:0]
:OUTPUT ACCEPT [38964:13133002]
-A INPUT -p udp -m udp --dport 5060 -j ACCEPT
-A INPUT -p udp -m udp --dport 4569 -j ACCEPT
-A INPUT -p udp -m udp --dport 5036 -j ACCEPT
-A INPUT -p udp -m udp --dport 10000:20000 -j ACCEPT
-A INPUT -p udp -m udp --dport 2727 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 5038 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 5060 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 4577 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 3306 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 873 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 443 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 21 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -p icmp -m icmp --icmp-type 8 -j ACCEPT
-A INPUT -s 127.0.0.1/32 -d 127.0.0.1/32 -j ACCEPT
-A INPUT -m state --state ESTABLISHED -j ACCEPT
COMMIT
EOF

scp -P${slavesshport} /etc/sysconfig/iptables ${slavehostname}:/etc/sysconfig/iptables
ssh -p${slavesshport} ${slavehostname} "sed -i 's/.*.dport 22 .*/-A INPUT -p tcp -m tcp --dport ${slavesshport} -j ACCEPT/' /etc/sysconfig/iptables"
ssh -p${slavesshport} ${slavehostname} "service iptables restart"

sed -i 's/.*.dport 22 .*/-A INPUT -p tcp -m tcp --dport '${mastersshport}' -j ACCEPT/' /etc/sysconfig/iptables
service iptables restart


service asterccd stop
if [ "$confstatus" = "HA" ];then
    chkconfig asterccd off
    ssh -p${slavesshport} ${slavehostname} "chkconfig asterccd off"
fi
service nginx stop
chkconfig nginx off
service php-fpm stop
chkconfig php-fpm off
ssh -p${slavesshport} ${slavehostname} "service asterccd stop"

ssh -p${slavesshport} ${slavehostname} "service nginx stop"
ssh -p${slavesshport} ${slavehostname} "chkconfig nginx off"
ssh -p${slavesshport} ${slavehostname} "service php-fpm stop"
ssh -p${slavesshport} ${slavehostname} "chkconfig php-fpm off"

service ntpd stop
ntpdate 0.pool.ntp.org
hwclock -w
service ntpd start
sleep 5
ssh -p${slavesshport} ${slavehostname} "service ntpd stop"
ssh -p${slavesshport} ${slavehostname} "ntpdate 0.pool.ntp.org"
ssh -p${slavesshport} ${slavehostname} "ntpdate ${masterip}"
ssh -p${slavesshport} ${slavehostname} "hwclock -w"
ssh -p${slavesshport} ${slavehostname} "sed -i 's/server 0.*/server ${masterip}/' /etc/ntp.conf"
ssh -p${slavesshport} ${slavehostname} "service ntpd start"

if [ "$confstatus" = "Cluster" ];then

    cat $curpath/cccs.txt | while read cslines
    do
        cshostname=`echo $cslines |cut -d " " -f1`
        csip=`echo $cslines |cut -d " " -f2`
        cssshport=`echo $cslines |cut -d " " -f3`

        echo "$csip $cshostname" >> /etc/hosts
        #echo $cslines
        ssh -p${cssshport} ${cshostname} "mkdir -p /root/.ssh"
        scp -P${cssshport} ~/.ssh/*  ${cshostname}:/root/.ssh
        ssh -p${cssshport} ${cshostname} "chmod 600 -R /root/.ssh"

        scp -P${cssshport} /etc/sysconfig/iptables ${cshostname}:/etc/sysconfig/iptables
        ssh -p${cssshport} ${cshostname} "service iptables restart"

        ssh -p${cssshport} ${cshostname} "service ntpd stop"
        ssh -p${cssshport} ${cshostname} "ntpdate ${masterip}"
        ssh -p${cssshport} ${cshostname} "hwclock -w"
        ssh -p${cssshport} ${cshostname} "sed -i 's/server 0.*/server ${masterip}/' /etc/ntp.conf"

        ssh -p${cssshport} ${cshostname} hostname ${cshostname}
        ssh -p${cssshport} ${cshostname} sed -i 's/HOSTNAME.*/HOSTNAME='${cshostname}'/' /etc/sysconfig/network
        ssh -p${cssshport} ${cshostname} "echo $masterip $masterhostname >> /etc/hosts"
        ssh -p${cssshport} ${cshostname} "echo $slaveip $slavehostname >> /etc/hosts"
        ssh -p${cssshport} ${cshostname} "echo $csip $cshostname >> /etc/hosts"
        #ssh -t -p${cssshport} ${cshostname} "ssh -p${mastersshport} ${masterhostname} \"echo ${cshostname} >> /root/testssh\""

    done
fi


configureMysqlconf
configRsync
configureHAconf


echo "/opt/asterisk/scripts/astercc/astcc_hacheck -d" >> /etc/rc.local

echo -e "\033[32mconfiguration finished\033[0m"
exit;
