#!/bin/bash
#

function gender_chrony_config() {
    >/tmp/chrony.conf
    cat >/tmp/chrony.conf <<EOF
driftfile /var/lib/chrony/drift
makestep 1.0 3
rtcsync
logdir /var/log/chrony

EOF

    if [ -z $NTPSERVER ]; then
        log_warning "未配置NTP服务器地址,将配置${IP_LIST[0]}为时间服务器server。"
        time_server=${IP_LIST[0]}
        cp /tmp/chrony.conf /tmp/chrony.server.conf
        cat >>/tmp/chrony.server.conf <<EOF1
server ntp.aliyun.com iburst
bindcmdaddress 0.0.0.0
allow 0.0.0.0/0
local stratum 10
EOF1
        $SCP /tmp/chrony.server.conf root@${IP_LIST[0]}:/tmp/chrony.conf.tmp
        echo "server ${time_server} iburst" >>/tmp/chrony.conf
        if [ ${#IP_LIST[@]} -gt 1 ];then
            for ((i = 1; i < ${#IP_LIST[@]}; i++)); do
                $SCP /tmp/chrony.conf root@${IP_LIST[$i]}:/tmp/chrony.conf.tmp
            done
        fi
    else
        how_many=$(echo ${NTPSERVER} | tr ',' ' ')
        for ((n = 0; n < ${#how_many[@]}; n++)); do
            echo "server ${NTPSERVER[$n]} iburst" >>/tmp/chrony.conf
        done
        for ((i = 0; i < ${#IP_LIST[@]}; i++)); do
            $SCP /tmp/chrony.conf root@${IP_LIST[$i]}:/tmp/chrony.conf.tmp
        done
    fi

}

function install() {
    gender_chrony_config
    for _ip in ${IP_LIST[@]}; do
        $SCP Install_Packages/chrony.tar.gz root@${_ip}:/tmp/
        $SSH root@${_ip} "tar xf /tmp/chrony.tar.gz -C /tmp/"
        $SSH root@${_ip} "rpm -ivh /tmp/chrony/libseccomp*.rpm"
        $SSH root@${_ip} "rpm -ivh /tmp/chrony/chrony*.rpm"
        $SSH root@${_ip} "mv /tmp/chrony.conf.tmp /etc/chrony.conf"
        $SSH root@${_ip} "systemctl restart chronyd && systemctl enable chronyd"
    done
}

# check the ntp server is validate or.
function post_install() {
    time_server_chrony=$(chronyc sources | awk '$1 ~ /\*/{if($1 !~ /?/) print "true"}')
    if [ ${time_server_chrony}x != "true"x ]; then
        server=$(chronyc sources | awk '{if($1 ~ /\*/ && $1 !~ /?|x/) print $2}')
        log_error "时间服务器${server[@]}不可用"
    else
        return
    fi
}

function install_ntpserver() {
    install
    sleep 30
    post_install
}
