#!/bin/bash

NTP_CONFIG="$BASEDIR/configs/ntp"

_install() {
    yum -y -q install ntp >/dev/null 2>&1

    if [ -f $NTP_CONFIG/ntp.conf ];then
        \cp -f $NTP_CONFIG/ntp.conf /etc/ntp.conf
    else
        PRINT_ERR "[ERROR] ntp.conf Not Found In $NTP_CONFIG"
	return 1
    fi

    #set timezone
    local tz_dir="/usr/share/zoneinfo/"
    for i in `seq 1 10`;
    do
        local tz=`/usr/bin/python $BASEDIR/utils/GetApolloConf.py regiontimezone $REGION`
        if [[ -n $tz ]];then
            break
        fi
        sleep 3
    done
    if [[ -n $tz ]];then
        rm -f /etc/localtime
        if [[ -e /etc/localtime ]];then
            PRINT_ERR "[ERROR] TimeZone File Delete Failed."
	    return 1
        else
            ln -s $tz_dir$tz /etc/localtime
            if [[ $? -ne 0 ]];then
                PRINT_ERR "[ERROR] TimeZone LinkFile Create Failed."
		return 1
            fi
        fi
    else
        PRINT_ERR "[ERROR] TimeZone Config Not Found In Apollo."
	return 1
    fi

    # add config from apollo
    local restrict_conf=""
    local server_conf=""
    local ntp_hosts=`/usr/bin/python $BASEDIR/utils/GetApolloConf.py regioninfo "$REGION".ntp`
    for host in $ntp_hosts;
    do
      local restrict_conf=$restrict_conf"restrict $host\n"
      local server_conf=$server_conf"server $host iburst minpoll 3 maxpoll 4 prefer\n"
    done

    sed -i "s/RESTRICT_CONF/$restrict_conf/g" /etc/ntp.conf
    sed -i "s/SERVER_CONF/$server_conf/g" /etc/ntp.conf

    if [[ $(cat /etc/ntp.conf |grep server|egrep -c "172|192|10") -eq 0 ]];then
        PRINT_ERR "[ERROR] Get NTP Config From Apollo Failed."
        return 1
    fi

    # 物理机同步写硬件时间
    if [[ $VMFLAG -eq 0 ]];then
        if [[ $OS = 'CentOS7' ]];then
            cat > /etc/sysconfig/ntpd <<EOF
OPTIONS="-g"
SYNC_HWCLOCK=yes
EOF
        elif [[ $OS = 'CentOS6' ]];then
            cat > /etc/sysconfig/ntpd <<EOF
OPTIONS="-u ntp:ntp -p /var/run/ntpd.pid -g"
SYNC_HWCLOCK=yes
EOF
        fi

        cat > /etc/cron.daily/hwclock <<EOF
#!/bin/sh
hwclock --systohc

EOF
        chown root:root /etc/cron.daily/hwclock
        chmod 755 /etc/cron.daily/hwclock
    fi

    #local ntpserver=$(cat /etc/ntp.conf |grep ^server | head -n2|tail -n1 | awk '{print $2}')
    #ntpdate $ntpserver > /dev/null 2>&1

    # 更优雅的开机同步时间，保证所有正确依赖ntpd的服务的启动后时间不会跳，千万别用rc.local加ntpdate
#    ntp_server1=`echo $ntp_hosts |awk '{print $1}'`
#    echo $ntp_server1 > /etc/ntp/step-tickers
#不写step-tickers，从ntp.conf自动尝试，更智能
    echo '' > /etc/ntp/step-tickers

    # 保证交付时重启后时间没误差
    service ntpd stop > /dev/null 2>&1
    service ntpdate start > /dev/null 2>&1
    hwclock --systohc

    service ntpd start > /dev/null 2>&1

    # 清空交付前系统日志
    for logfile in /var/log/*
    do
         if [[ -f "$logfile" ]]; then
            echo '' > "$logfile"
        fi
    done
}

_check() {
    _check="PASS"

    #check timezone
    local tz_dir="/usr/share/zoneinfo/"
    local tz=`/usr/bin/python $BASEDIR/utils/GetApolloConf.py regiontimezone $REGION`

    if [[ -n $tz ]];then
        local md5_tz=`md5sum $tz_dir$tz|awk '{print $1}'`
        local md5_localtime=`md5sum /etc/localtime|awk '{print $1}'`
        if [[ $md5_tz != $md5_localtime ]];then
            _check="FAIL"
            PRINT_ERR "[ERROR] Copy TIMEZONE File Failed."
        fi
    else
        _check="FAIL"
        PRINT_ERR "[ERROR] TimeZone Config Not Found In Apollo."
    fi
    service ntpd status > /dev/null 2>&1
    if [[ $? -ne 0 ]]; then
        _check="FAIL"
        PRINT_ERR "[ERROR] ntpd Is Not Running."
    fi

    if [ ! -s "/etc/ntp.conf" ];then
        _check="FAIL"
        PRINT_ERR "[ERROR] File /etc/ntp.conf Is Empty."
    fi

    if [[ $(date | grep -c "UTC") -eq 1 ]]; then
        _check="FAIL"
        PRINT_ERR "[ERROR] Timezone Is UTC, Not Correct."
    fi

    if [[ $VMFLAG -eq 0 ]];then
        if [[ ! -x /etc/cron.daily/hwclock ]];then
            _check="FAIL"
            PRINT_ERR "[ERROR] /etc/cron.daily/hwclock can not execute"
        fi
    fi

    if [[ $(cat /etc/ntp.conf |grep server|egrep -c "172|192|10") -eq 0 ]];then
        _check="FAIL"
        PRINT_ERR "[ERROR] Get NTP Config From Apollo Failed."
    fi

}
